Exact Change(01背包)
描述
- 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.
輸入
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
輸出
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.
樣例輸入
1
1400
3
500
1000
2000
樣例輸出
1500 2
題目大意:
已知一件物品的價格,和n個有價值的硬幣,現在求這些硬幣能湊成的不小於這件物品的價格的最小價值。
01背包。
#include <bits/stdc++.h> using namespace std; const int INF=0x3f3f3f3f; int dp[10005],a[105]; int main() { ios::sync_with_stdio(false); int T; cin>>T; while(T--) { memset(dp,INF,sizeof dp); dp[0]=0; int k,n; cin>>k>>n; for(int i=0;i<n;i++) cin>>a[i]; for(int i=0;i<n;i++) for(int j=10004;j>=a[i];j--)///最大的可能值開始 dp[j]=min(dp[j],dp[j-a[i]]+1); int pos; for(int i=k;i<10005;i++) if(dp[i]!=INF) {pos=i;break;} cout<<pos<<‘ ‘<<dp[pos]<<‘\n‘; } return 0; }
Exact Change(01背包)