描述
Charlie is a driver of Advanced Cargo Movement, Ltd. Charlie drives a lot and so he often buys coffee at coffee vending machines at motorests. Charlie hates change. That is basically the setup of your next task.
Your program will be given numbers and types of coins Charlie has and the coffee price. The coffee vending machines accept coins of values 1, 5, 10, and 25 cents. The program should output which coins Charlie has to use paying the coffee so that he uses as many coins as possible. Because Charlie really does not want any change back he wants to pay the price exactly.
输入
Each line of the input contains five integer numbers separated by a single space describing one situation to solve. The first integer on the line P, 1 <= P <= 10 000, is the coffee price in cents. Next four integers, C1, C2, C3, C4, 0 <= Ci <= 10 000, are the numbers of cents, nickels (5 cents), dimes (10 cents), and quarters (25 cents) in Charlie's valet. The last line of the input contains five zeros and no output should be generated for it.
输出
For each situation, your program should output one line containing the string "Throw in T1 cents, T2 nickels, T3 dimes, and T4 quarters.", where T1, T2, T3, T4 are the numbers of coins of appropriate values Charlie should use to pay the coffee while using as many coins as possible. In the case Charlie does not possess enough change to pay the price of the coffee exactly, your program should output "Charlie cannot buy coffee.".
题目意思:有 4 种硬币,给出咖啡的价格和四种硬币的数量,求出能买到咖啡的最多硬币数量,并输出每一种硬币对应的数量,如果买不到咖啡,就输出不能买到。
用二进制优化的多重背包做,要记录路径。
dp[i] 表示 i 元钱时,硬币最多是多少。
ans[i][j] 表示 i 元钱时,第 j 种硬币的数量是多少。
在进行状态转移的时候,更新下 ans 数组,最后输出 ans[p] 的四种硬币数量就行了。
#include <iostream> #include <cstring> using namespace std; const int MAX = 10500; int dp[MAX]; //价值为 i 时,最多多少枚硬币 int v[5] = {0, 1, 5, 10, 25}; int num[5]; int ans[MAX][5]; //价值为 i 时,四种硬币的数量,此时硬币数量和最多(等于dp[i]) int p; void zeroOne(int i, int j); //第 i 个物品,数量为 j int main(){ // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); while(scanf("%d", &p)){ int sum = 0; for(int i=1; i<=4; i++){ scanf("%d", num+i); sum += num[i] * v[i]; } if(sum == 0 && p == 0){ break; } //钱不够 if(sum < p){ printf("Charlie cannot buy coffee. "); continue; } //DP 多重背包 memset(dp, -1, sizeof(dp)); memset(ans, 0, sizeof(ans)); dp[0] = 0; for(int i=1; i<=4; i++){ int j; for(j=1; j<=num[i]; j=(j<<1)){ //转化成0-1背包进行二进制优化 zeroOne(i, j); } j = num[i]; zeroOne(i, j); } if(dp[p] != -1){ printf("Throw in %d cents, %d nickels, %d dimes, and %d quarters. ", ans[p][1], ans[p][2], ans[p][3], ans[p][4]); }else{ printf("Charlie cannot buy coffee. "); } } return 0; } void zeroOne(int i, int j){ for(int k=p-j*v[i]; k>=0; k--){ if(dp[k] != -1){ //如果 k 状态存在 if(dp[k] + j > dp[k+j*v[i]]){ //从 k 状态出发,到 k + j*v[i] 状态,如果所用硬币比原来要多 int nk = k+j*v[i]; dp[nk] = dp[k] + j; memcpy(ans[nk], ans[k], sizeof(ans[k])); //更新记录的硬币数量 ans[nk][i] += j; //相比 k 状态多放了 j 个 i } } } num[i] -= j; }