7-2 凑零钱 (30 分)
韩梅梅喜欢满宇宙到处逛街。现在她逛到了一家火星店里,发现这家店有个特别的规矩:你可以用任何星球的硬币付钱,但是绝不找零,当然也不能欠债。韩梅梅手边有 10^4 枚来自各个星球的硬币,需要请你帮她盘算一下,是否可能精确凑出要付的款额。
输入格式:
输入第一行给出两个正整数:N(≤104)是硬币的总个数,M(≤102)是韩梅梅要付的款额。第二行给出 N 枚硬币的正整数面值。数字间以空格分隔。
输出格式:
在一行中输出硬币的面值 V1≤V2≤⋯≤Vk,满足条件 V1+V2+…+Vk=M。数字间以 1 个空格分隔,行首尾不得有多余空格。若解不唯一,则输出最小序列。若无解,则输出 No Solution。
注:我们说序列{ A[1],A[2],⋯ }比{ B[1],B[2],⋯ }“小”,是指存在 k≥1 使得 A[i]=B[i] 对所有 i<k 成立,并且 A[k]<B[k]。
输入样例 1:
8 9
5 9 8 7 2 3 4 1
输出样例 1:
1 3 5
输入样例 2:
4 8
7 2 4 3
输出样例 2:
No Solution
收获
1 使用容器进行少设置一个长度变量用必要时可用r.size()解决
2 使用exit(0)可以少设置一个标志位
3 不要把正确结果的情况排除掉
4 递归真香
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int n,m,sum,temp;
int used[10010];
vector<int> coin,result;//vector can be used as array
void search(int curmoney){
if(curmoney==m){
for(int i=0;i<result.size();i++){
if(i!=0){
cout<<" ";
}
cout<<result[i];
}
exit(0);// Please exit after you complete your output
}
for(int i=0;i<n&&curmoney<m;i++){
if(!used[i]&&(curmoney+coin[i])<=m){//Dont't delete the situation of the right answer
result.push_back(coin[i]);
used[i]=1;
search(curmoney+coin[i]);
result.pop_back();
used[i]=0;
}
}
}
int main(){
cin>>n>>m;
for(int i=0;i<n;i++){
cin>>temp;
sum+=temp;
coin.push_back(temp);
}
sort(coin.begin(),coin.end());
if(sum>=m){//Dont't delete the situation of the right answer
search(0);//The original sum of money is 0;
}
cout<<"No Solution\n";
return 0;
}
//参考代码
#include <bits/stdc++.h>
using namespace std;
int dp[10010];
int w[10010];
bool choice[10010][10010];
bool cmp(int a,int b){return a > b;}
int main() {
// Input begin
int n,m;
cin>>n>>m;
for(int i = 1;i <= n;i++){
cin>>w[i];
}
// Input end
sort(w + 1,w + n + 1,cmp); //sort it
for(int i = 1;i <= n;i++){ //
for(int j = m;j >= w[i];j--){
if(dp[j] <= dp[j - w[i]] + w[i]){
choice[i][j] = true;
dp[j] = dp[j - w[i]] + w[i];
}
}
}
vector<int> res;
if(dp[m] != m) cout<<"No Solution"<<endl;
else{
int v = m, index = n;
while(v > 0) {
if(choice[index][v] == true) {
res.push_back(w[index]);
v -= w[index];
}
index--;
}
for(int i = 0;i < res.size();i++) {
if(i != 0) cout<<" ";
cout<<res[i];
}
}
return 0;
}