// 集训最终開始了。来到水题先 #include <cstdio> #include <cstring> #include <algorithm> #include <iostream> using namespace std; int a[23]; int d[23][100000]; int flag[23]; int W,n; void init(){ cin >> n; for (int i=1;i<=n;i++) cin >> a[i]; memset(flag,0,sizeof(flag)); memset(d,0,sizeof(d)); } void print(int x,int y){ if (y<=0||x<1) return ; //cout << x << " " << y << endl; if (d[x][y]==d[x-1][y]){ flag[x] = 0; print(x-1,y); //return ; }else if (d[x][y]==d[x-1][y-a[x]] + a[x]){ flag[x] = 1; //cout << a[x] << " "; print(x-1,y-a[x]); //return ; } } void solve(){ for (int i=1;i<=n;i++){ for (int j=W;j>=0;j--){ d[i][j] = d[i-1][j]; if (j>=a[i]) d[i][j] = max(d[i-1][j],d[i-1][j-a[i]] + a[i]); } } print(n,W); for (int i=1;i<=n;i++) if (flag[i]) printf("%d ",a[i]); printf("sum:%d\n",d[n][W]); } int main(){ //freopen("1.txt","r",stdin); while(cin >> W){ init(); solve(); } }
时间: 2024-10-02 02:34:56