HDU 5936 Difference(折半枚举)

20 篇文章 0 订阅
9 篇文章 0 订阅

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值