http://poj.org/problem?id=1787
Charlie’s Change
Time Limit: 1000MS Memory Limit: 30000K
Total Submissions: 4238 Accepted: 1325
Description
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.
Input
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.
Output
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.”.
Sample Input
12 5 3 1 2
16 0 0 0 1
0 0 0 0 0
Sample Output
Throw in 2 cents, 2 nickels, 0 dimes, and 0 quarters.
Charlie cannot buy coffee.
体会
本蒻写这道题写懵了的,后来看大牛的代码才懂是怎么回事…
#include<iostream>
#include<cstdio>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=1e4+5;
const int inf = 1<<20;
int dp[maxn];
int path[maxn];
int used[maxn];
int ans[26];
int main(){
int key,num[5];
int w[5]={0,1,5,10,25};
while(scanf("%d%d%d%d%d",&key,&num[1],&num[2],&num[3],&num[4]) ){
if(!key&&!num[1]&&!num[2]&&!num[3]&&!num[4]) break;
memset(path,0,sizeof(path));
memset(ans,0,sizeof(ans));
for(int i=0;i<=key+1;i++)
dp[i]=-inf;
dp[0]=0;
path[0]=-1;
for(int i=1;i<=4;i++){
memset(used,0,sizeof(used));//有了这个东西是区分 dp[j]和used[j];
for(int j=w[i];j<=key;j++){
if(dp[j]<dp[j-w[i]]+1 && dp[j-w[i]]>=0 &&used[j-w[i]]<num[i]){
dp[j]=dp[j-w[i]]+1;//dp[j]表示容量j买了w[i]后总的硬币数
used[j]=used[j-w[i]]+1;//used[j]表示容量j买了w[i]后的硬币数(只在买w[i]这一轮)
path[j]=j-w[i];// path[j]表示容量j买了w[i]后的容量
}
}
}
//printf("%d\n",inf);
if(dp[key] < 0){
printf("Charlie cannot buy coffee.\n");
}
else{
int i=key;
while(path[i]!=-1){
ans[i-path[i]]++;
i=path[i];
}
printf("Throw in %d cents, %d nickels, %d dimes, and %d quarters.\n",
ans[w[1]],ans[w[2]],ans[w[3]],ans[w[4]]);
}
}
return 0;
}