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.
12 5 3 1 2 16 0 0 0 1 0 0 0 0 0
Throw in 2 cents, 2 nickels, 0 dimes, and 0 quarters. Charlie cannot buy coffee.
Source: Czech Technical University Open 2003
题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2156
分析:这题还是付钱的问题,做法依旧是多重背包,比较不一样的是这题要求出背包的具体装法,也就是记录一下转移路径就行了
代码:
#include<cstdio> using namespace std; const int mm=11111; int v[]= {1,5,10,25}; int f[mm],p[mm],t[mm],c[4],ans[4]; int i,j,m; void CompletePack(int v,int k) { for(int i=v;i<=m;++i) if(f[i-v]>=0&&f[i]<=f[i-v]) { f[i]=f[i-v]+1; p[i]=i-v; t[i]=k; } } void ZeroOnePack(int v,int d,int k) { for(int i=m;i>=v;--i) if(f[i-v]>=0&&f[i]<f[i-v]+d) { f[i]=f[i-v]+d; p[i]=i-v; t[i]=k; } } int main() { while(scanf("%d%d%d%d%d",&m,&c[0],&c[1],&c[2],&c[3]),m+c[0]+c[1]+c[2]+c[3]) { for(i=0; i<=m; ++i)f[i]=-1000000000; f[0]=0; for(i=0; i<4; ++i) if(c[i]) { if(c[i]*v[i]>=m)CompletePack(v[i],i); else { j=1; while(j<c[i]) { ZeroOnePack(v[i]*j,j,i); c[i]-=j; j<<=1; } ZeroOnePack(v[i]*c[i],c[i],i); } } if(f[m]>=0) { for(i=0; i<4; ++i)ans[i]=0; while(m) { ans[t[m]]+=(m-p[m])/v[t[m]]; m=p[m]; } printf("Throw in %d cents, %d nickels, %d dimes, and %d quarters.\n",ans[0],ans[1],ans[2],ans[3]); } else puts("Charlie cannot buy coffee."); } return 0; }