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.
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 |
题意:求k个不相同的指数的b进制的和在[x, y]中
思路:数位DP,但要注意的是只有系数为1的情况,所以每位只能是0,1,至于不相同的只要是取1 的时候不不相同,至于0是不变的
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;
const int maxn = 50;
int n, m, b, k;
int num[maxn], dp[maxn][maxn];
int dfs(int cur, int cnt, int flag) {
if (cur == -1)
return cnt == k;
if (!flag && dp[cur][cnt] != -1)
return dp[cur][cnt];
int end = flag?num[cur]:b-1;
int ans = 0;
for (int i = 0; i <= end && i <= 1; i++)
ans += dfs(cur-1, cnt+i, flag&&(i==end)); //+1数才会变化
if (!flag)
dp[cur][cnt] = ans;
return ans;
}
int cal(int x) {
int len = 0;
while (x) {
num[len++] = x%b;
x /= b;
}
return dfs(len-1, 0, 1);
}
int main() {
memset(dp, -1, sizeof(dp));
while (scanf("%d%d%d%d", &n, &m, &k, &b) != EOF) {
int ans = cal(m) - cal(n-1);
printf("%d\n", ans);
}
return 0;
}