参考了别人的博客,这道题不太懂。http://blog.csdn.net/tiantangrenjian/article/details/17334201
#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;
int n,m;
int arr[100008];
int f[10008][108];
int has[10008][108];
bool cmp(int a,int b){
return a>b;
}
int main(){
int second;
memset(has, 0, sizeof(has));
memset(f, 0, sizeof(f));
//freopen("/Users/pantingting/Documents/code/data/input", "r", stdin);
scanf("%d%d",&n,&m);
for (int i=1; i<=n; i++) {
scanf("%d",&arr[i]);
}
sort(arr+1,arr+n+1,cmp);
f[0][0]=0;
for (int i=1; i<=n; i++) {
for (int j=1; j<=m; j++) {
if (j-arr[i]<0) {
second=0;
}else
second=f[i-1][j-arr[i]]+arr[i];
if (f[i-1][j]>second) {
f[i][j]=f[i-1][j];
has[i][j]=0;
}
else{
f[i][j]=second;
has[i][j]=1;
}
}
}
if (f[n][m]!=m) {
printf("No Solution");
}
else{
//printf("f[n][m]=%d\n",f[n][m]);
int first=0;
while (m&&n) {
while(has[n][m]==0){
n--;
}
if (first==0) {
first=1;
printf("%d",arr[n]);
}
else
printf(" %d",arr[n]);
m-=arr[n];
n--;
}
}
printf("\n");
return 0;
}