ural1057Amount of Degrees-数位dp

来源:互联网 发布:如何删掉淘宝评价图片 编辑:程序博客网 时间:2024/05/17 07:44

题目地址:http://acm.timus.ru/problem.aspx?space=1&num=1057

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 andY, separated with a space (1 ≤ X ≤ Y ≤ 231−1). The next two lines contain integersK and B (1 ≤ K ≤ 20; 2 ≤ B ≤ 10).

Output

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

Sample

inputoutput
15 2022
3



题目大意
从x-y这个区间找满足条件的整数的个数:这个数恰好等于k个不相等b的整数幂之和


解题思路
因为所求数为不相等的整数幂之和,所以系数只能是1或者0,这样一来,所有进制都和二进制相似了。以下先以二进制为例
本题满足区间减法,即从x-y中合法的个数等于0-y的个数减去0-x-1的个数。所以我们只需要知道从0-n的个数就可以了
假设n=13,k=3,那么这道题就转化为从0-13的二进制数中找出有三个1的数有几个,给出一颗高度为4的二叉树表示所有4位二进制数
根节点为0,由根节点开始,1101最高位数是1,走向树的右儿子,此时需要计算蓝色子树中有3个1的个数,再向1101的下一位走,还是1,此时再统计绿色子树中有2个1的个数(因为绿色子树的根节点已经有一个1了),再向下走一位是0,再向下走一位是1,此时再统计紫色子树中有1个1的个数。发现每次都是向右子树走的话才会统计它对应的左子树。
接下来的问题就是如何统计一个高度为i的二叉树中恰有j个1的个数。递推方程 f【i,j】=f【i-1】【j】+ f【i-1】【j-1】,我们预处理f,用假想的完全二叉树每次从根走向右儿子的时候统计它左儿子中的个数。
最后的问题就是如何处理非二进制?前面提到了系数只能是1或者是0,也就是我们假想的b叉树只有0和1的儿子是能用的,那么和二叉树就差不多了。如果一个3进制的数某一位是2,那么这个数是不能够用3的幂加和得到的,所以我们找一个最接近n的并且系数只有1 和0的数:从高位起找到第一个不为0 1的位 将其及其之后的数都改为1。然后视为二进制来做就可以。

代码:
#include <cstring>#include <iostream>#include <algorithm>#include <cstdio>using namespace std;int x,y,k,b;int f[40][40];//高度为i的树有j个1的 方案数void init(){    f[0][0]=1;    for(int i=1;i<=35;++i)    {        f[i][0]=f[i-1][0];//不管高度是几,有0个1的方案数都相同。        for(int j=1;j<=i;++j)            f[i][j]=f[i-1][j]+f[i-1][j-1];//左子树+右子树。5    }}int exchange(int n,int b)//把n换成b进制后,将非1、0位变为1后再当成2进制转为十进制得数{    int i=0,num=0,ans=0;    int t[40]={0};    while(n>0)    {        t[num++]=n%b;        n/=b;    }    i=num-1;    while(t[i]<=1) i--;//最高位开始找到第一个不是0或1的    while(i>=0)    {        t[i]=1;//从这位开始后面都取1,才能得到跟这个数n最接近的数        i--;    }    while(num>=0)//转化为十进制    {        ans=ans*2+t[num];        num--;    }    return ans;}int cacl(int x,int k){    int ans=0,tot=0;    for(int i=31;i>0;--i)//从高位的开始找    {        if(x & (1<<i))        {            tot++;            if(tot>k) break;            x ^= (1<<i);        }        if(x & 1<<(i-1))//下一位还是1(向右子树走)        {            ans+=f[i-1][k-tot];        }    }    if(x+tot==k) ans++;//上面循环并没有到0,单独判断高度为0,需要注意的是现在这个x已经变了,要么是1要么是0;    return ans;}int main(){    scanf("%d%d%d%d",&x,&y,&k,&b);    init();    if(b==2)    {        printf("%d\n",cacl(y,k)-cacl(x-1,k));    }    else    {        x=exchange(x,b);        y=exchange(y,b);        printf("%d\n",cacl(y,k)-cacl(x-1,k));    }    return 0;}



1 0