1068 Find More Coins (30分)
作者:CHEN, Yue
单位:浙江大学
代码长度限制:16 KB
时间限制:400 ms
内存限制:64 MB
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 1
Sample Output 1:
1 3 5
Sample Input 2:
4 8
7 2 4 3
Sample Output 2:
No Solution
题意:
给定目标值和一组数列,选出数列中能组合成目标值的数,若有多组,输出序列最小的组合。
思路:
若将数列从小到大排列,用dfs深度优先解题最后一个测试案例会超时。不妨把问题想象成,背包容量为m,选出序列最小的刚好装满背包的问题。物品的价值即为物品的重量,所以仅当物品的价值等于目标值才满足要求。用动态规划的01背包模板解题。
for(int i=1;i<n;i++){
for(int j=m;j>=w[i];j--)
dp[j]=max(dp[j],dp[j-w[i]]+c[i]);
}。
这里有一个技巧,就是将数列从大到小排列,先将重量大的物品进行放入,然后判断dp[j]<=dp[j-w[i]]+c[i],当等于号成立时,会将小序列的组合覆盖掉大重量的组合。这样就达到了目的,用一个二维数组记录dp的变化过程,方便输出,具体可以通过代码体会。
参考代码:
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 10010;
int n, m;
int dp[maxn] = {0}, coin[maxn];
bool flag[maxn][101] = {false};
bool cmp(int a, int b) { return a > b; }
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)scanf("%d", &coin[i]);
sort(coin + 1, coin + n + 1, cmp);
for (int i = 1; i <= n; i++) {
for (int j = m; j >= coin[i]; j--) {
if (dp[j] <= dp[j - coin[i]] + coin[i]) {
dp[j] = dp[j - coin[i]] + coin[i];
flag[i][j] = true;
}
}
}
if (dp[m] != m)printf("No Solution\n");
else {
int index = n;
while (m > 0) {
if (flag[index][m]) {
printf("%d", coin[index]);
m -= coin[index];
if (m != 0)printf(" ");
}
index--;
}
}
return 0;
}
如有错误,欢迎指正