
Description
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
Output
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.
【题意】给出p,c1,c2,c3,c4,p是总金额,c1,c2,c3,c4分别是给出的四种面值的硬币的数量,求合起来是p使用最多硬币的情况下,各种硬币都用了多少。
【思路】背包。并且要记录各种硬币的数量,用一个数组path[p],path[p]=p-v[i];p-path[p]=v[i];巧用path解决了各种硬币数量的问题。接着背包问题,他是限定数量的,要判断num[j-v[i]]是否小于c[i],还要判定dp[j]是否存在即是否大于0,以及dp[j-v[i]]+1是否大于dp[j].
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int N=;
int p;
int v[]= {,,,,};
int c[];
int dp[N],num[N],path[N],ans[N];
int main()
{
while(~scanf("%d%d%d%d%d",&p,&c[],&c[],&c[],&c[]))
{
if(!p&&!c[]&&!c[]&&!c[]&&!c[]) break;
memset(dp,,sizeof(dp));
memset(ans,,sizeof(ans));
memset(path,,sizeof(path));
dp[]=;
for(int i=; i<=; i++)//背包
{
memset(num,,sizeof(num));//每个i更新,都要初始化
for(int j=v[i]; j<=p; j++)
{
if(num[j-v[i]]<c[i]&&dp[j-v[i]]&&dp[j-v[i]]+>dp[j])
{
dp[j]=dp[j-v[i]]+;
num[j]=num[j-v[i]]+;
path[j]=j-v[i];
} }
}
int i=p;
if(dp[p]>)//判断是否存在
{
while(i!=)
{
ans[i-path[i]]++;//巧用path,进行路径记录
i=path[i];
}
printf("Throw in %d cents, %d nickels, %d dimes, and %d quarters.\n",ans[],ans[],ans[],ans[]);
}
else printf("Charlie cannot buy coffee.\n");
}
return ;
}