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.
在输出时要从后向前遍历,因为价值小的可能延伸不到后面,不用担心个数问题因为循环时限制了个数变多时才更新
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 10010;
int a[N], path[10][N], dp[N], used[N];
int main()
{
int p;
int v[]={1,5,10,25};
while(scanf("%d %d %d %d %d",&p, &a[0], &a[1], &a[2], &a[3]),p||a[0]||a[1]||a[2]||a[3])
{
memset(dp,-1,sizeof(dp));
memset(path,0,sizeof(path));
dp[0]=0;
for(int i=0;i<4;i++)
{
memset(used,0,sizeof(used));
for(int j=v[i];j<=N;j++)
{
if(dp[j-v[i]]>=0&&dp[j-v[i]]+1>dp[j]&&used[j-v[i]]<a[i])
{
dp[j]=dp[j-v[i]]+1;
used[j]=used[j-v[i]]+1;
path[i][j]=used[j];
}
}
}
if(dp[p]>=0)
{
int x[N]={0};
for(int i=3;i>=0;i--)
{
x[i]=path[i][p];
p-=(x[i]*v[i]);
}
printf("Throw in %d cents, %d nickels, %d dimes, and %d quarters.\n",x[0], x[1], x[2], x[3]);
}
else
{
printf("Charlie cannot buy coffee.\n");
}
}
return 0;
}