1068 Find More Coins (30 分)
题意:找出和为m的序列,且满足字典序最小。
题解:背包问题。
- dp[i][j]表示没有第i个物品,价值≤j的最大价值。choice[i][j]是否存在。
- 对硬币从大到小排序。保证最后拿的价值最小,字典序最小。
- 最后开始倒着选择,找出答案。
代码:
#include <bits/stdc++.h>
using namespace std;
int const N = 1e4 + 10;
int const M = 1e2 + 10;
int n,m,a[N];
int dp[M],choice[N][M];
int main(){
ios::sync_with_stdio(false);
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>a[i];
sort(a + 1,a + 1 + n,greater<int>());
for(int i=1;i<=n;i++){
for(int j=m;j>=a[i];j--){
if(dp[j] <= dp[j-a[i]] + a[i]){
dp[j] = dp[j-a[i]] + a[i];
choice[i][j] = true;
}
}
}
if(dp[m] != m){
cout<<"No Solution"<<endl;
}else{
vector<int>ans;
int index = n;
while(m > 0){
if(choice[index][m]){
ans.push_back(a[index]);
m -= a[index];
}
index--;
}
for(int i=0;i<ans.size();i++){
cout<<ans[i];
if(i == ans.size() - 1) cout<<endl;
else cout<<' ';
}
}
return 0;
}