典型的0/1背包問題。
int main(int argc, char const* argv[])
{
int n;
int m;
int dp[2000];
int put[25][2000];
while(scanf("%d",&n) != EOF){
vector<int> cd;
memset(dp,0,sizeof(dp));
memset(put,0,sizeof(put));
scanf("%d",&m);
while(m--){
int l;
scanf("%d",&l);
cd.push_back(l);
}
for(size_t i = 0;i<cd.size();i++){
for(int j = n;j >=cd[i];j--){
if(dp[j]<dp[j-cd[i]]+cd[i]){
dp[j] = dp[j-cd[i]]+cd[i];
put[i][j] = true;
}
}
}
bool first = true;
int sum = 0;
for(int i = cd.size()-1,j = n;i >= 0;i--){
if(put[i][j] && first){
printf("%d",cd[i]);
sum = sum+cd[i];
first = false;
j = j-cd[i];
}else if(put[i][j]){
printf(" %d",cd[i]);
sum = sum+cd[i];
j = j-cd[i];
}
}
printf(" sum:%d\n",sum);
}
return 0;
}