# Ural - 1057. Amount of Degrees

## 1057. Amount of Degrees

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 = 24+20,
18 = 24+21,
20 = 24+22.
Input
The first line of input contains integers X and Y, separated with a space (1XY2311$1 ≤ X ≤ Y ≤ 2^31−1$). The next two lines contain integers K and B (1K20;2B10$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

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=100;
int X,Y;
int K,B;
int dig[maxn];
int dp[maxn][20][25];
int dfs(int cur,int e,int s)
{
if(cur<0)return s==K;
if(s>K)return 0;
if(!e&&dp[cur][s][K]!=-1)
return dp[cur][s][K];
int end=(e?min(1,dig[cur]):1);
int ans=0;
for(int i=0;i<=end;i++)
ans+=dfs(cur-1,e&&i==dig[cur],s+(i!=0));//这里一定注意要是i==dig[cur]，因为前面的end是变化过的
if(!e)dp[cur][s][K]=ans;
return ans;
}
int solve(int x)
{
int len=0;
memset(dp,-1,sizeof(dp));
while(x)
{
dig[len++]=x%B;
x/=B;
}
return dfs(len-1,1,0);
}
int main()
{
while(scanf("%d%d",&X,&Y)!=EOF)
{
scanf("%d%d",&K,&B);
printf("%d\n",solve(Y)-solve(X-1));
}
return 0;
}

10-27 2014

08-14 274

07-28 538

07-17 449

09-20 2177

08-18 562

07-27 891

04-10 1040

08-08 278

03-15 258