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
排序后深搜;
简单的深搜有2个测试点会超时,可以通过标记搜过的值来剪枝,因为只需要找到1次就足够,所以搜索过的都可以标记;
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;
bool flag = false;
bool No[105] = {false};
int coin[10005] = {0};
int pay, n, total = 0;
vector<int> ans, save;
void dfs(int left)
{
if(No[total])//如果当前总值之前已经搜索过直接结束
return ;
else if(total == pay)//第一次找到则保存
{
if(!flag)
{
flag = true;
ans = save;
}
return ;
}
for(int i=left; i<n; i++)
{
if(flag || total+coin[i] > pay)//找到了或者总值过大都不需要继续搜索;
break;
No[total] = true;//标记搜索过,注意不能写在total变更之后,这样回溯的时候会判定已经搜索过
total += coin[i];
save.push_back(coin[i]);
dfs(i+1);
total -= coin[i];//回溯
save.pop_back();
}
}
int main()
{
scanf("%d%d", &n, &pay);
for(int i=0; i<n; i++)
{
scanf("%d", &coin[i]);
}
sort(coin, coin+n);
dfs(0);
if(ans.empty())
printf("No Solution\n");
else
{
for(int i=0; i<ans.size(); i++)
{
if(i==0)
printf("%d", ans[i]);
else
printf(" %d", ans[i]);
}
}
return 0;
}