1068. Find More Coins (30)
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 104 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 (<=104, the total number of coins) and M(<=102, 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 V1 <= V2 <= ... <= Vk such that V1 + V2 + ... + Vk = 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 1Sample Output 1:
1 3 5Sample Input 2:
4 8 7 2 4 3Sample Output 2:
No Solution
解题思路:此题为01背包问题,设f[n][m]为从前n个面值里面选取的面值综合不不超过m的最大面值。对每个面值的硬币,都有选与不选两种可能,故状态转移方程为
f[n][m]=max{f[n-1][m],f[n-1][m-c[n]]+c[n]}
最后,若f[n][m]恰好等于m,则说明存在问题的解;否则,答案不存在,输出“No Solution”。
数组大小的判断:为了简便起见,可将硬币面值从大到小排序,则从前向后遍历时,若某个面值的硬币被选中,则之后最小的所有答案中最小的面值将被选中。逆序之后即保证了所求得的数组为最小数组。时间复杂度为O(n*m)。代码如下:
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 10001;
const int maxm = 101;
int f[maxn][maxm] = { 0 };
bool has[maxn][maxm] = { 0 };
int* c = NULL;
int cal(int n, int m){
int i, j;
int sec;
for (int i = 1; i <= n; i++){
for (int j = 1; j <= m; j++){
if (j - c[i] < 0) sec = 0;
else sec = f[i - 1][j - c[i]] + c[i];
if (f[i - 1][j]>sec)
f[i][j] = f[i - 1][j];
else{
f[i][j] = sec;
has[i][j] = 1;
}
}
}
return f[n][m];
}
bool cmp(const int& a, const int& b){
return a > b;
}
int main(){
int n, m;
cin >> n >> m;
c = new int[n + 1];
memset(c, 0, sizeof(c));
int i;
for (i = 0; i < n; i++)
cin >> c[i + 1];
sort(c + 1, c + n + 1, cmp);
int res = cal(n, m);
if (res == m){
vector<int>v;
while (m){
while (!has[n][m])
n--;
v.push_back(c[n]);
m -= c[n];
n--;
}
for (int i = 0; i < v.size(); i++){
if (i>0)
cout << " ";
cout << v[i];
}
cout << endl;
}
else cout << "No Solution" << endl;
delete c;
return 0;
}