URAL - 1057

Time Limit: 1000MS   Memory Limit: 65536KB   64bit IO Format: %I64d & %I64u

Status

Description

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

input output
15 20
2
2
3

Source

Problem Source: Rybinsk State Avia Academy

其实是做完这个题才做的nefu的题的,论文讲的太粗狂了,看了标称才写对==我上午超级不理解的地方是为什么当发现当前位>1时,我们加的是f[i+1][k-tot]?为啥这货就代表全都选啊啊啊。我们想想f[i][j]的递推表达式是f[i][j]=f[i-1][j]+f[i-1][j-1]前者表示左子树的根节点是0,后者表示右子树的根节点是1,所以f[i+1][j]就表示长度为i时的所以情况啦!

/***********
ural1057
2016.2.16
396	1ms	G++ 4.9
***********/
#include <iostream>
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
int f[32][32];
void init()
{
    f[0][0]=1;
    for(int i=1;i<=31;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 cal(int n,int k,int b)
{
    vector<int>c;
    int ans=0,tot=0;
    while(n)
    {
        c.push_back(n%b);
        n/=b;
    }
    for(int i=c.size()-1;i>=0;i--)
    {
        if(c[i]==1)
        {
            ans+=f[i][k-tot];
            tot++;
            if(tot>=k) break;
        }
        if(c[i]>1)
        {
            ans+=f[i+1][k-tot];
            break;
        }
    }
    if(tot==k) ans++;
    return ans;
}
int main()
{
  // freopen("cin.txt","r",stdin);
    init();
    int x,y,b,k;
   // printf("15,4 %d\n",change(15,4));
    while(~scanf("%d%d",&x,&y))
    {
        scanf("%d%d",&k,&b);
        printf("%d\n",cal(y,k,b)-cal(x-1,k,b));
    }
    return 0;
}