题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4734
题目大意:
对于一个 \(n\) 位十进制数 \(x\) (\(A_nA_{n-1}A_{n-2} \cdots A_2A_1\)),我们定义
\[F(x)=A_n \times 2^{n-1} + A_{n-1} \times 2^{n-2} + \cdots + A_2 \times 2 + A_1 \times 1\]
现在给你两个数 \(A\) 和 \(B\) ,请计算出区间 \([0,B]\) 范围内有多少 \(\le F(A)\) 的数。(\(0 \le A,B \lt 10^9\))
解题思路:
首先 \(A \le 10^9\) 所以 \(F(A)\) 的最大值为
\[F(999999999) = 9 \times (2^8+2^7+ \cdots + 2^0) = 9 \times (2^9-1) = 4599\]
所以对于任意一个 \(\lt 10^9\) 的 \(x\) 来说, \(F(x) \le 4599\) 。
我们可以用 数位DP 来解决这个问题。
我们设状态 \(f[pos][num]\) 来表示当前数位在 \(pos\) 且剩余值不超过 \(num\) 的方案数。
然后我们开函数 dfs(int pos, int num, bool limit)
进行求解,其中:
pos
表示当前所处数位;num
表示剩余数值(也就是pos
位开始的数不能超过num
);limit
表示当前是否处于限制状态。
实现代码如下:
#include <bits/stdc++.h> using namespace std; int f[33][5000], a[33]; void init() { memset(f, -1, sizeof(f)); } int dfs(int pos, int num, bool limit) { if (pos < 0) return 1; if (!limit && f[pos][num] != -1) return f[pos][num]; int up = limit ? a[pos] : 9; int tmp = 0; for (int i = 0; i <= up; i ++) { int t = i * (1<<pos); if (t > num) break; tmp += dfs(pos-1, num-t, limit && i==up); } if (!limit) f[pos][num] = tmp; return tmp; } int get_num(int x, int num) { int pos = 0; while (x) { a[pos++] = x % 10; x /= 10; } return dfs(pos-1, num, true); } int T, A, B, num; int F(int x) { int res = 0, t = 1; while (x) { res += t * (x%10); x /= 10; t *= 2; } return res; } int main() { init(); scanf("%d", &T); for (int cas = 1; cas <= T; cas ++) { scanf("%d%d", &A, &B); num = F(A); printf("Case #%d: %d\n", cas, get_num(B, num)); } return 0; }