URAL 1057. Amount of Degrees (数位DP)

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 exactlyK 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 = 24+20,
18 = 24+21,
20 = 24+22.

Input

The first line of input contains integers X and Y, separated with a space (1 ≤ X ≤ Y ≤ 231−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的整数次幂之和。例如,设X=15,Y=20,K=2,B=2,则有且仅有下列三个数满足题意:
    17 = 2^4+2^0,   
   18 = 2^4+2^1,
    20 = 2^4+2^2.
1 ≤ X ≤ Y ≤ 2^31−1,1 ≤ K ≤ 20,  2 ≤ B ≤ 10。 

实质上:求[X,Y] 区间转化为 B 进制 1 的个数为K 的数的出现次数。

题解:数位DP。

注意:只有系数为1的情况,所以每位只能是0,1,至于不相同的只要是取1 的时候不不相同,至于0是不变的。


大体思路:
所求的数为互不相等的幂之和,亦即其B进制表示的各位数字都只能是0和1。

因此,我们只需讨论二进制的情况,其他进制都可以转化为二进制求解。

本题区间满足区间减法,因此可以进一步简化问题:令count[i..j]表示[i..j]区间内合法数的个数,则

count[i..j]=count[0..j]-count[0..i-1]。

换句话说,给定n,我们只需求出从0到n有多少个符合条件的数。

步骤:
首先预处理f。

f[i,j]代表i位二进制数中恰好有j个1的数的个数。

f[i,j]=f[i-1,j]+f[i-1,j-1]

计算count[0..n]

像前几题一样,一位一位枚举,只需要多记录后面需要的1的个数即可。

if digit[i] = 1 then ans = ans + f[i,need]

need就是后面需要的1的个数。

AC代码:
#include <stdio.h>
#include <cstring>
#include <vector>
#include <algorithm>
#include <string.h>
using namespace std;
int digit[33];
typedef long long LL;
const int N = 50;
int f[N][N]; //f[i][j]表示前i个中选 j 个 1的个数
void init()
{
    f[0][0] =  1;
    for(int i=1;i<33;i++)
	{
        f[i][0] = f[i-1][0];
        for(int j=1;j<=i;j++)
        {
        	f[i][j] = f[i-1][j] + f[i-1][j-1];
		 } 
            
    }
}
int solve(int x,int k,int B)
{
	int len=-1;
    //vector<int> v;
    while(x)
    {
    	digit[++len]=x%B; 
        //v.push_back(x%B);
        x/=B;
    }
    int cnt = 0,ans = 0;
    for(int i=len;i>=0;i--)
    {
        if(digit[i]==1) // 如果为 1,则依次求解
        {
            ans+=f[i][k-cnt]; //need 
            cnt++;
            if(cnt==k)
                break;
        }
        else if(digit[i]>1) //假如大于1的话,相当于所有的位可以为 1,所以直接求解跳出
        {
            ans += f[i+1][k-cnt];
            break;
        }
    }
    if(cnt==k)
        ans++;
    return ans;
}
int main()
{
    init();
    int x,y,k,B;
    while(~scanf("%d%d%d%d",&x,&y,&k,&B))
    {
        printf("%d\n",solve(y,k,B)-solve(x-1,k,B));
    }
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值