原题链接:http://vjudge.net/problem/URAL-1057
题意:[ x , y ]里一共有多少个数可以由k个b整数幂组成。
#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
#include<vector>
#include<cstring>
#include<queue>
#include<stack>
#include<algorithm>
#include<cmath>
#include<string>
#include<stdio.h>
#define INF 99999999
#define eps 0.0001
using namespace std;
int dp[35][35];//dp[i][j]表示深度为i有j个1的种类,根深度为0
int x, y, k, b;
int cnt[35];
void init()
{
for (int i = 0; i <= 31; i++)
{
dp[i][0] = 1;
for (int j = 1; j <= i; j++)
dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1];
}
}
int solve(int n)
{
int len = 0;
int ans = 0;
int ik = k;
int ib = b;
while (n)
{
cnt[len++] = n%ib;
n /= ib;
}
for (int i = len - 1; i >= 0; i--)
{
if (cnt[i] == 1)
{
ans += dp[i][ik];//以0开头,找到k个1;然后k--,固定开头为1,继续做
ik--;
}
else if (cnt[i] > 1)
{
ans += dp[i + 1][ik];
break;
}
if (ik < 0)//注意是小于0
return ans;
}
if (ik == 0)//n本身满足
ans++;
return ans;
}
int main()
{
init();
while (~scanf("%d%d%d%d", &x, &y, &k, &b))
{
printf("%d\n", solve(y) - solve(x - 1));
}
return 0;
}