POJ 2282 數位DP


鏈接:

http://poj.org/problem?id=2282

題意:

給你一個區間a,b,問a到b之間每個數字出現了多少次

題解:

看過算法設計與分析的人都很熟悉這道題,畢竟是課后練習的第一道,感覺用數位dp比模擬更好理解啊

dp[pos][sta]表示到從最低位到第pos位,第pos位為sta(0<=sta<=9)時的 num的個數。

代碼:

31 int a[20];
32 int dp[20][10];
33 int num;
34 
35 int dfs(int pos, int sta, bool lead, bool limit) {
36     if (pos == -1) return sta;
37     if (!lead && !limit && dp[pos][sta] != -1) return dp[pos][sta];
38     int up = limit ? a[pos] : 9;
39     int res = 0;
40     rep(i, 0, up + 1) {
41         if (lead && i == 0) res += dfs(pos - 1, sta, true, limit && i == a[pos]);
42         else res += dfs(pos - 1, sta + (i == num), false, limit && i == a[pos]);
43     }
44     if (!lead && !limit) dp[pos][sta] = res;
45     return res;
46 }
47 
48 int solve(int x) {
49     int pos = 0;
50     while (x) {
51         a[pos++] = x % 10;
52         x /= 10;
53     }
54     return dfs(pos - 1, 0, true, true);
55 }
56 
57 int main() {
58     ios::sync_with_stdio(false), cin.tie(0);
59     int a, b;
60     memset(dp, -1, sizeof(dp));
61     while (cin >> a >> b, a) {
62         if (a > b) swap(a, b);
63         num = 0;
64         cout << solve(b) - solve(a - 1);
65         for (num = 1; num <= 9; num++)
66             cout << ' ' << solve(b) - solve(a - 1);
67         cout << endl;
68     }
69     return 0;
70 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM