HDU 5936 Difference(折半枚举)

来源:互联网 发布:创意美工作品图片大全 编辑:程序博客网 时间:2024/06/07 20:25

Difference

Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1247 Accepted Submission(s): 335

Problem Description
Little Ruins is playing a number game, first he chooses two positive integers y and K and calculates f(y,K), here

f(y,K)=∑z in every digits of yzK(f(233,2)=22+32+32=22)

then he gets the result

x=f(y,K)−y

As Ruins is forgetful, a few seconds later, he only remembers K, x and forgets y. please help him find how many y satisfy x=f(y,K)−y.

Input
First line contains an integer T, which indicates the number of test cases.

Every test case contains one line with two integers x, K.

Limits
1≤T≤100
0≤x≤109
1≤K≤9

Output
For every test case, you should output ‘Case #x: y’, where x indicates the case number and counts from 1 and y is the result.

Sample Input
2
2 2
3 2

Sample Output
Case #1: 1
Case #2: 2

Source
2016年中国大学生程序设计竞赛(杭州)

Recommend
liuyiding

题目大意

  输入两个正整数x,k(0x109,1k9),问有多少个正整数y满足y的每一位数字的k次方减去y等于x.

解题思路

  虽然题目没有给y的数据范围,但是可以发现如果y很大的时候计算的结果是负数,所以可以估计出来y最多只有10位数字。
  知道这个后就可以想到一个最暴力的方法,每次枚举所有可能的y,统计答案。虽然这样毫无疑问会TLE,但是我们可以发现对于y的各位数字对答案的贡献是相互独立的,所以我们就可以考虑使用折半搜索,枚举后5位打一张表,然后枚举前5位在后面查询。总复杂度O(105log105)
  最后还有一个优化,由于k只有9种可能,而测试组数有100组,所以我们可以先预处理出各个k的情况下后5位的表。
  需要注意题目还有一个坑点,由于题面说y是正整数,当x==0的时候需要额外减掉y==0的一个方案。

AC代码

#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>#include <map>using namespace std;#define LL long long#define mem(a,b) memset((a),(b),sizeof(a))const int ten[]={1, 10, 100, 1000, 10000, 100000};int X, K;int Pow[13][13];//i的j次方map<LL, int> cnt[10];//贡献为i的方案数void pre_work()//预处理{    for(int i=0;i<=9;++i)    {        Pow[i][0]=1;        for(int j=1;j<=9;++j)            Pow[i][j]=Pow[i][j-1]*i;    }    for(int k=1;k<=9;++k)//枚举所有可能的k    {        for(int i=0;i<=99999;++i)//枚举后5位        {            LL res=-i;            for(int j=0;j<=4;++j)                res+=Pow[i/ten[j]%10][k];            ++cnt[k][res];        }    }}int main(){    pre_work();    int T_T;    scanf("%d", &T_T);    for(int cas=1;cas<=T_T;++cas)    {        scanf("%d%d", &X, &K);        LL ans=0;        for(int i=0;i<=99999;++i)//枚举前5位        {            LL res=-i*100000ll;            for(int j=0;j<=4;++j)                res+=Pow[i/ten[j]%10][K];            LL obj=X-res;            if(cnt[K].find(obj)!=cnt[K].end())                ans+=cnt[K][obj];        }        if(X==0)//特判X==0            --ans;        printf("Case #%d: %lld\n", cas, ans);    }    return 0;}
原创粉丝点击