Exact Change
Problem C: Exact Change
- Seller: That will be fourteen dollars.
- Buyer: Here's a twenty.
- Seller: Sorry, I don't have any change.
- Buyer: OK, here's a ten and a five. Keep the change.
Of course, you would like to minimize the amount you pay (though you must pay at least as much as the value of the item). Moreover, while paying the minimum amount, you would like to minimize the number of coins or bills that you pay out.
Input Specification
The first line of input contains one integer specifying the number of test cases to follow. Each test case begins with a line containing an integer, the price in cents of the item you would like to buy. The price will not exceed 10 000 cents (i.e., $100). The following line contains a single integer n, the number of bills and coins that you have. The number n is at most 100. The following n lines each contain one integer, the value in cents of each bill or coin that you have. Note that the denominations can be any number of cents; they are not limited to the values of coins and bills that we usually use in Canada. However, no bill or coin will have a value greater than 10 000 cents ($100). The total value of your bills and coins will always be equal to or greater than the price of the item.Sample Input
1 1400 3 500 1000 2000
Output Specification
For each test case, output a single line containing two integers: the total amount paid (in cents), and the total number of coins and bills used.Output for Sample Input
1500 2
给定一个账单,和各种面值的钱各一张,要求输出要付的钱和硬币的个数,付的钱要大于等账单。因为每种面值的钱数量都是1,类似不完全背包。
#include<iostream> #define maxn 10010 using namespace std; int dp[maxn]; int coin[110]; int min(int a,int b){ return a<b?a:b; } int main(){ int n,amount,m; while(cin>>n){ while(n-->0){ cin>>amount>>m; for(int i=0;i<m;i++){ cin>>coin[i]; } for(int i=1;i<maxn;i++) dp[i]=maxn; dp[0]=0; for(int i=0;i<m;i++){ for(int j=maxn-1;j>=coin[i];j--){ dp[j]=min(dp[j-coin[i]]+1,dp[j]); } } if(dp[amount]==maxn){ for(int i=amount+1;i<maxn;i++){ if(dp[i]!=maxn){ cout<<i<<" "<<dp[i]<<endl; break; } } } else cout<<amount<<" "<<dp[amount]<<endl; } } return 0; }