L3-001 凑零钱
动态规划+记录方案
const int maxn = 1e4+10,maxm = 1e2+10;
int dp[maxn][maxm];
int fa[maxm];
int a[maxn];
int main(void)
{
int N,M;cin>>N>>M;
for(int i = 1;i <= N; ++i) cin>>a[i];
sort(a+1,a+N+1);
for(int i = 0;i <= M; ++i)
fa[i] = -1;
fa[0] = 0;
for(int i = N;i >= 1; --i){
for(int j = M;j >= a[i]; --j){
if(fa[j-a[i]] != -1)
dp[i][j] = fa[j-a[i]],fa[j] = i;
}
}
// for(int i = 1;i <= M; ++i)
// cout<<dp[1][i]<<endl;
if(fa[M] == -1)
puts("No Solution");
else
{
// cout<<fa[M]<<endl;
int j = M;
bool first = true;
for(int now = fa[j];now != 0;){
if(first)first = false;
else putchar(' ');
printf("%d",a[now]);
int tmp = j-a[now];
now = dp[now][j];
j = tmp;
// cout<<j<<endl;
}
// printf("%d",j);
}
return 0;
}