思路:就是一个数位DP,相当于统计有k位为1的b进制数,数位DP即可
代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int l, r, k, b;
int bit[50], bn, dp[50][50];
void get(int x) {
bn = 0;
if (x == 0) bit[bn++] = 0;
while (x) {
bit[bn++] = x % b;
x /= b;
}
for (int i = 0; i < bn / 2; i++)
swap(bit[i], bit[bn - i - 1]);
}
int cal(int num) {
get(num);
memset(dp, 0, sizeof(dp));
int flag = 0, cnt = 0;
for (int i = 0; i < bn; i++) {
for (int j = 0; j <= k; j++) {
for (int x = 0; x < 2; x++) {
dp[i + 1][j + x] += dp[i][j];
}
}
if (flag) continue;
for (int x = 0; x < min(bit[i], 2); x++)
dp[i + 1][cnt + x]++;
if (bit[i] >= 2) flag = 1;
cnt += bit[i];
if (cnt > k) flag = 1;
}
return dp[bn][k] + (!flag && cnt == k);
}
int main() {
while (~scanf("%d%d%d%d", &l, &r, &k, &b)) {
printf("%d\n", cal(r) - cal(l - 1));
}
return 0;
}