传送门:https://www.patest.cn/contests/pat-a-practise/1068
AC 代码 .典型的BFS 并进行剪枝处理,有方案时剩下的不用执行 因为此方案必定是最小的.
#include <iostream>
#include <vector>
#include <stdio.h>
#include <algorithm>
#include <queue>
#include <string.h>
#include <unordered_map>
#include <map>
using namespace std;
vector<vector<int>>allCase;
void bfs(int targetMoney,vector<int>coins,int start,vector<int>curPath,bool &flag){
for (int i=start; i<coins.size(); i++) {
int diff = targetMoney - coins[i];
if(diff==0){
curPath.push_back(coins[i]);
allCase.push_back(curPath);
flag = true;
break;
}else if(diff>0){
curPath.push_back(coins[i]);
bfs(diff, coins, i+1, curPath,flag);
if(flag)//有方案
break;
curPath.pop_back();
}else
return;
}
}
int main(){
int n,money,sum=0;
scanf("%d %d",&n,&money);
vector<int>coins(n);
for (int i=0; i<n; ++i) {
scanf("%d",&coins[i]);
sum = sum + coins[i];
}
if(money>sum){
printf("No Solution\n");
return 0;
}
sort(coins.begin(),coins.end());
bool flag = false;
bfs(money, coins, 0, vector<int>(),flag);
sort(allCase.begin(), allCase.end(), [](vector<int>a,vector<int>b){
if(a.size()!=b.size())
return a.size()>b.size();
else
for (int i=0; i<a.size(); ++i) {
if(a[i]!=b[i])
return a[i]<b[i];
}
return false;
});
if (allCase.size()==0)
printf("No Solution\n");
else
for (int i=0; i<allCase[0].size(); ++i) {
printf(i==allCase[0].size()-1?"%d\n":"%d ",allCase[0][i]);
}
return 0;
}