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 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
such that
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 is said to be “smaller” than sequence if there exists such that for all , and .
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
Ω
在给定数组中找到一串数之和等于给定值A,如果有多个解则取最小序列。
没什么好的想法,先排序后枚举。从最小的数开始,往后依次累加找到就return。虽然说是枚举,但为了不超时还是需要有避免无意义枚举的前验工作和停止的条件。
首先如果所有数总和都没有到A,那么直接“No Solution”;如果刚好==A,那么直接把排序完数组打印一遍。在枚举过程中如果当前单个数值>remain,说明无解及时停止。
看了一些题解,基本是用01背包的思想来求的。把所有数都看成是重量与价值都一致的物品,然后背包限制就是A,那么我们只要用01背包的思路来求解最大价值即可,如果最大价值<A说明无解,==A则有解。01背包是一种动态规划算法,即自底向上,也不失为一剂良策。最近被学校操作系统实验整的头疼,就不实现了(逃
🐎
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> coins, solution;
bool search(int s, int amt)
{
for (int i = s; i < coins.size(); ++i)
{
if (coins[i] > amt)
return false;
else if (amt == coins[i])
{
solution.push_back(coins[i]);
return true;
}
solution.push_back(coins[i]);
int rem = amt - coins[i];
for (int j = i + 1; j < coins.size(); ++j)
if (search(j, rem))
return true;
solution.pop_back();
}
return false;
}
int main()
{
int n, a, sum = 0;
cin >> n >> a;
coins.resize(n);
for (auto &c: coins)
{
cin >> c;
sum += c;
}
sort(coins.begin(), coins.end());
if (sum < a)
cout << "No Solution" << endl;
else if (sum == a)
for (int i = 0; i < coins.size(); ++i)
cout << (i == 0 ? "" : " ") << coins[i];
else
{
if (search(0, a))
for (int i = 0; i < solution.size(); ++i)
cout << (i == 0 ? "" : " ") << solution[i];
else
cout << "No Solution" << endl;
}
}