B - CD UVA - 624
https://cn.vjudge.net/contest/224070#problem/B
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <vector> 5 #include <cmath> 6 #include <algorithm> 7 using namespace std; 8 #define N 100005 9 #define mod 530600414 10 #define mem(a,b) memset(a,b,sizeof(a)) 11 #define ll long long 12 int n,m; 13 int w[30]; 14 int dp[N]; 15 bool pre[30][N]; 16 int main() 17 { 18 while(~scanf("%d%d",&n,&m)){ 19 mem(pre,0); 20 mem(dp,0); 21 for(int i=0;i<m;i++) scanf("%d",&w[i]); 22 for(int i=m-1;i>=0;i--) {//要按输入顺序输出 23 for(int j=n;j>=w[i];j--){ 24 if(dp[j]<dp[j-w[i]]+w[i]){ 25 dp[j]=dp[j-w[i]]+w[i]; 26 pre[i][j]=1; 27 } 28 } 29 } 30 int j=n; 31 for(int i=0;i<m&&j>0;i++){//从前往后查询,因此上面的更新要从后往前 32 if(pre[i][j]){ 33 printf("%d ",w[i]); 34 j-=w[i]; 35 } 36 } 37 printf("sum:%d\n",dp[n]); 38 } 39 return 0; 40 }