首页 > 代码库 > HDU 4734 F(x) 数位DP

HDU 4734 F(x) 数位DP

题目链接

求[0,B]这段区间多少数的F(x)不大于F(A)。

F(A),求出来,之后的就是数位dp,dp[len][st]表示长度为len,之前各位上数字的花费为F(A)-st的数有多少个,记忆化搜索就好。

<style>pre { font-family: monospace; color: #ffffff; background-color: #000000 } body { font-family: monospace; color: #ffffff; background-color: #000000 } .lnr { color: #ffff00 } .Special { color: #ffd7d7 } .Statement { color: #ffff00 } .Type { color: #87ffaf } .Constant { color: #ff40ff } .PreProc { color: #5fd7ff }</style>
技术分享
 1 #include <stdio.h>
 2 #include <string.h>
 3 const int maxn = 9;
 4 int a[9], dp[maxn][4600];
 5 int dfs(int len, int st, int limit) {
 6     if (len < 0)
 7         return st >= 0;
 8     if (st < 0)
 9         return 0;
10     if (!limit && dp[len][st] != -1)
11         return dp[len][st];
12     int end = limit ? a[len] : 9, ans = 0;
13     for (int i = 0; i <= end; ++i)
14         ans += dfs(len - 1, st - (1 << len) * i, limit && i == end);
15     if (!limit)
16         dp[len][st] = ans;
17     return ans;
18 }
19 int main() {
20     int T;
21     scanf("%d", &T);
22     memset(dp, -1, sizeof(dp));
23     for (int Tc = 1; Tc <= T; ++Tc) {
24         int A, B, FA = 0, len = 0;
25         scanf("%d%d", &A, &B);
26         for (int i = 0; A; ++i, A /= 10)
27             FA += (A % 10) << i;
28         do {
29             a[len++] = B % 10;
30             B /= 10;
31         } while (B);
32         printf("Case #%d: %d\n", Tc, dfs(len - 1, FA, 1));
33     }
34     return 0;
35 }
View Code

 

HDU 4734 F(x) 数位DP