您的位置:首页 > 其它

Ural 1057. Amount of Degrees 数位统计

2013-07-28 20:26 337 查看


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

inputoutput
15 20
2
2

3

Problem Source: Rybinsk State Avia Academy
/** 
 *
 *求给定区间[X,Y]中满足下列条件的整数个数:这个数恰好等于K 个互不相等的B的整数次幂之和。
 *令count[i..j]表示[i..j]区间内合法数的个数,则count[i..j]=count[0..j]-count[0..i-1]。换句话说,给定n,我们只需求出从0 到n有多少个符合条件的数。
 *设f[i,j]表示所求,则分别统计左右子树内符合条件数的个数,有f[i,j]=f[i-1,j]+f[i-1,j-1]。
 *详见 刘聪 的论文
 *
 */     

#include<iostream>
using namespace std;
int num[33],C[33][33];
int find(int x,int k,int b)
{
    int ans=0,l=0;
    while(x)
    {
        num[l++]=x%b;
        x/=b;
    }
    int temp=0;
    for(int i=l-1; i>=0; --i)
    {
        if(num[i]>1)
        {
            ans+=C[i+1][k-temp];
            break;
        }
        else if(num[i]==1)
        {
            if(i>=k-temp)
                ans+=C[i][k-temp];
            temp++;
            if(temp>k)
                break;
        }
        if(!i&&temp==k)
            ans++;
    }
    return ans;
}
int main()
{
    int x,y,k,b;
    for(int i=0; i<=20; ++i) for(int j=i; j<=31; ++j)
            if(!i||i==j)
                C[j][i]=1;
            else
                C[j][i]=C[j-1][i]+C[j-1][i-1];
    cin>>x>>y>>k>>b;
    cout<<find(y,k,b)-find(x-1,k,b)<<endl;
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: