HDU 5936 Difference ( 2016 CCPC 杭州 D && 折半枚举 )

题目链接

题意 : 给出一个 x 和 k 问有多少个 y 使得 x = f(y, k) - y 、f(y, k) 为 y 中每个位的数的 k 次方之和、x ≥ 0

分析 :

f(y, k) - y = x ≥ 0

可得 x > y

所以满足条件的 y 最多不超过 10 位

变化一下式子

x = f(a, k) - a + f(b, k) - b * (1e5)

x - f(a, k) + a = f(b, k) - b * (1e5)

那么先处理出等式右边的 f(b,k) - b*(1e5)

这个的复杂度是大于但是不怎么大于 O(1e5 * 9)

然后再从 0 ~ 1e5 枚举 a 用二分查找出满足条件的数的个数

#include<bits/stdc++.h>
#define LL long long
using namespace std;

const int maxn = 1e5 + 10;
LL F[maxn][15];
vector<LL> num;
LL x, k;

LL Qpow(LL a, int b)
{
    LL ret = 1;
    while(b){
        if(b & 1) ret = ret * a;
        a = a * a;
        b >>= 1;
    }return ret;
}

LL GetF(int i, int j)
{
    LL ret = 0;
    while(i){
        ret += Qpow((LL)(i%10), j);
        i /= 10;
    }return ret;
}

inline void init()
{
    for(int i=0; i<=(int)1e5; i++)
        for(int j=1; j<=9; j++)
            F[i][j] = GetF(i, j);
}

LL Solve()
{
    num.clear();

    for(int i=0; i<=(int)1e5; i++) num.push_back(F[i][k] - 1LL * i * (LL)1e5);

    sort(num.begin(), num.end());

    LL ret = 0;
    for(int i=0; i<=(int)1e5; i++)
        ret += upper_bound(num.begin(), num.end(), x - F[i][k] + i) -
               lower_bound(num.begin(), num.end(), x - F[i][k] + i);

    return ret - (LL)(x == 0);
}

int main(void)
{
    init();

    int nCase;
    scanf("%d", &nCase);

    for(int T=1; T<=nCase; T++){

        scanf("%lld %lld", &x, &k);

        printf("Case #%d: %lld\n", T, Solve());
    }
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/LiHior/p/9979473.html