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
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(const int& a, const int& b) {
return a > b;
}
int main() {
int n, m;
vector<int> vec, ans;
int dp[102][10010], trace[102][10010];
//int dp[15][15], trace[15][15];
scanf("%d %d", &n, &m);
vec.push_back(0);
for (int i = 1; i <= n; ++i)
{
int tmp = 0;
scanf("%d", &tmp);
vec.push_back(tmp);
}
memset(dp, 0, sizeof(dp));
memset(trace, 0, sizeof(trace));
sort(vec.begin()+1, vec.end(), cmp);
for (int i = 0; i <= n; ++i)
{
dp[0][i] = 1;
}
for (int i = 1; i <= n; ++i)
{
for (int j = vec[i]; j <= m; ++j)
{
if(dp[j-vec[i]][i-1] == 1) {
dp[j][i] = 1;
trace[j][i] = i;
} else {
dp[j][i] = dp[j][i-1];
trace[j][i] = trace[j][i-1];
}
}
}
if(dp[m][n] == 0) {
printf("No Solution\n");
} else {
int tmp = trace[m][n], curTotal = m;
while(curTotal != 0 && tmp != 0) {
int i = tmp;
ans.push_back(vec[i]);
curTotal -= vec[i];
tmp = trace[curTotal][i-1];
}
for (int i = 0; i < ans.size(); ++i)
{
if(i == 0)
printf("%d", ans[i]);
else
printf(" %d", ans[i]);
}
printf("\n");
}
return 0;
}
本文介绍了一种解决特定硬币组合以精确支付给定金额的问题。通过使用动态规划算法,该文详细解释了如何从大量硬币中找出能够构成指定金额的最小硬币序列,并给出了完整的C++实现代码。
887

被折叠的 条评论
为什么被折叠?



