poj1787 Charlie's Change

Posted 王宜鸣

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj1787 Charlie's Change相关的知识,希望对你有一定的参考价值。

思路:

完全背包,记录路径。

实现:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int INF = 0x3f3f3f3f;
 4 int v[4] = {1, 5, 10, 25};
 5 int c[4], m;
 6 int dp[10005], used[10005], path[10005];
 7 int main()
 8 {
 9     while (cin >> m >> c[0] >> c[1] >> c[2] >> c[3], m || c[0] || c[1] || c[2] || c[3])
10     {
11         memset(used, 0, sizeof used);
12         memset(path, 0, sizeof path);
13         path[0] = -1;
14         for (int i = 0; i <= m; i++) dp[i] = -INF;
15         dp[0] = 0;
16         for (int i = 0; i < 4; i++)
17         {
18             memset(used, 0, sizeof used);
19             for (int j = v[i]; j <= m; j++)
20             {
21                 if (dp[j - v[i]] != -INF && dp[j - v[i]] + 1 > dp[j] && used[j - v[i]] < c[i])
22                 {
23                     dp[j] = dp[j - v[i]] + 1;
24                     used[j] = used[j - v[i]] + 1;
25                     path[j] = j - v[i];
26                 }
27             }
28         }
29         if (dp[m] <= -INF) { cout << "Charlie cannot buy coffee." << endl; }
30         else 
31         {
32             int ans[26]; memset(ans, 0, sizeof ans);
33             while (path[m] != -1)
34             {
35                 ans[m - path[m]]++;
36                 m = path[m];
37             }
38             cout << "Throw in " << ans[v[0]] << " cents, " << ans[v[1]] << " nickels, " << ans[v[2]] << " dimes, and " << ans[v[3]] << " quarters." << endl;
39         }
40     }
41     return 0;
42 }

 

以上是关于poj1787 Charlie's Change的主要内容,如果未能解决你的问题,请参考以下文章

poj1787 Charlie's Change

POJ 1787 Charlie&#39;s Change

Charlie's Change POJ - 1787 (完全背包+记录路径)

poj 1787 背包+记录路径

POJ - 1787 (多重背包还原路径|| 完全背包)

Charlie's Change_完全背包&&路径记录