【数位DP】URAL 1057 Amount of Degrees

1057. Amount of Degrees

Time limit: 1.0 second
Memory limit: 64 MB
Create a code to determine the amount of integers, lying in the set [ X; Y] and being a sum of exactly K different integer degrees of  B.
Example. Let  X=15,  Y=20,  K=2,  B=2. By this example 3 numbers are the sum of exactly two integer degrees of number 2:
17 = 2 4+2 0,
18 = 2 4+2 1,
20 = 2 4+2 2.

Input

The first line of input contains integers  X and  Y, separated with a space (1 ≤  X ≤  Y ≤ 2 31−1). The next two lines contain integers  K and  B (1 ≤  K ≤ 20; 2 ≤  B ≤ 10).

Output

Output should contain a single integer — the amount of integers, lying between  X and  Y, being a sum of exactly  K different integer degrees of  B.

Sample

input output
15 20
2
2
3
题目大意:给出区间[X,Y],给出K和B,求区间内有多少个数可以被拆分成不同的K个B的幂的和,例如17可以被拆成2^4+2^0等。
现在不妨把B看做进制,如果将满足条件的十进制数A转化为B进制,则一定包含K个1和Len-K个0。
于是我们设dp[pos][cnt]表示到第pos位,填放了cnt个1的方案数,然后做记忆化搜索即可。
至于为什么恰好为K个1,是因为拆分出的幂必须是互不相同的,也就是说不存某一位上的数大于1。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;

#define MAXLEN 32
#define MAXNUM 10
#define INF 0x3f3f3f3f
typedef long long int LL;

int dp[MAXLEN+10][MAXLEN+5];
int Num[MAXLEN+10];
int Len;

int X,Y,K,B;

void GetNum(int x)
{
    memset(Num,0,sizeof(Num));
    Len=0;

    while(x)
    {
        Num[++Len]=x%B;
        x/=B;
    }

    return;
}

int dfs(int pos,int used,bool lim)
{
    if(used>K)return 0;
    if(pos<=0)return used==K;

    if(!lim&&dp[pos][used]!=-1)
        return dp[pos][used];

    int Nmax,ans=0;

    Nmax=lim?Num[pos]:B-1;
    if(0<=Nmax)ans+=dfs(pos-1,used,lim&&0==Nmax);
    if(1<=Nmax)ans+=dfs(pos-1,used+1,lim&&1==Nmax);

    if(!lim)dp[pos][used]=ans;

    return ans;
}

int GetAns(int x)
{
    GetNum(x);

    return dfs(Len,0,1);
}

int main()
{
    memset(dp,-1,sizeof(dp));

    scanf("%d%d%d%d",&X,&Y,&K,&B);
    printf("%d\n",GetAns(Y)-GetAns(X-1));
}

/*
1 2
1 2
*/


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值