1068 Find More Coins

Eva loves to collect coins from all over the universe, including some other planets like Mars. One day she visited a universal shopping mall which could accept all kinds of coins as payments. However, there was a special requirement of the payment: for each bill, she must pay the exact amount. Since she has as many as 1 coins with her, she definitely needs your help. You are supposed to tell her, for any given amount of money, whether or not she can find some coins to pay for it.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive numbers: N (≤, the total number of coins) and M (≤, the amount of money Eva has to pay). The second line contains N face values of the coins, which are all positive numbers. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the face values V​1​​≤V​2​​≤⋯≤V​k​​ such that V​1​​+V​2​​+⋯+V​k​​=M. All the numbers must be separated by a space, and there must be no extra space at the end of the line. If such a solution is not unique, output the smallest sequence. If there is no solution, output "No Solution" instead.

Note: sequence {A[1], A[2], ...} is said to be "smaller" than sequence {B[1], B[2], ...} if there exists k≥1 such that A[i]=B[i] for all i<k, and A[k] < B[k].

Sample Input 1:

8 9
5 9 8 7 2 3 4 1
 

Sample Output 1:

1 3 5
 

Sample Input 2:

4 8
7 2 4 3
 

Sample Output 2:

No Solution

题意:

  在给出的n个硬币中,选出几个硬币,使选出的这些硬币之和为m。如果存在多个解,则输出序列较小的那个。

思路:

  这是一道01背包的问题,根据背包的容量来判断当前的硬币是选还是不选,如果选取的话就要更新背包的容量状态,另外用select[i][j]来表示当背包体积为j的时候,物品i是否在背包中。用来最后判断背包中的物品。

Code:

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 int main() {
 6     int n, m;
 7     cin >> n >> m;
 8     vector<int> coins(n+1, 0);
 9     vector<int> dp(m+5, 0);
10     bool choice[10005][105] = {false};
11     for (int i = 1; i <= n; ++i) cin >> coins[i];
12     sort(coins.begin()+1, coins.end(), greater<int>());
13     for (int i = 1; i <= n; ++i) {
14         for (int j = m; j >= coins[i]; --j) {
15             if (dp[j] <= dp[j - coins[i]] + coins[i]) {
16                 dp[j] = dp[j - coins[i]] + coins[i];
17                 choice[i][j] = true;
18             }
19         }
20     }
21     if (dp[m] != m)
22         cout << "No Solution";
23     else {
24         vector<int> ans;
25         int volume = m, index = n;
26         while (volume > 0) {
27             if (choice[index][volume]) {
28                 ans.push_back(coins[index]);
29                 volume -= coins[index];
30             }
31             --index;
32         }
33         for (int i = 0; i < ans.size(); ++i) {
34             if (i == 0)
35                 cout << ans[i];
36             else
37                 cout << " " << ans[i];
38         }
39     }
40     cout << endl;
41     return 0;
42 }
永远渴望,大智若愚(stay hungry, stay foolish)
原文地址:https://www.cnblogs.com/h-hkai/p/12826633.html