只要每次都保存前k优解就可以了
注意当价值一样时,只算一种,所以要进行去重复 的操作
用到了unique,
1 2 2 4 0 0
unique之后1 2 4 0 0 2
3 5 10 2 1 2 3 4 5 5 4 3 2 1 5 10 12 1 2 3 4 5 5 4 3 2 1 5 10 16 1 2 3 4 5 5 4 3 2 1
12 2 0
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <limits.h>
#include <ctype.h>
#include <string.h>
#include <string>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <stack>
#include <deque>
#include <vector>
#include <set>
#include <map>
using namespace std;
int dp[1111][33];
int cost[111];
int val[111];
int mark[111];
bool cmp(int a,int b){
return a>b;
}
int main(){
int T,n,v,i,j,k,kk;
int con;
while(~scanf("%d",&T)){
while(T--){
memset(dp,0,sizeof(dp));
memset(cost,0,sizeof(cost));
memset(val,0,sizeof(val));
scanf("%d%d%d",&n,&v,&k);
for(i=1;i<=n;i++){
scanf("%d",&val[i]);
}
for(i=1;i<=n;i++){
scanf("%d",&cost[i]);
}
for(i=1;i<=n;i++){
for(j=v;j>=cost[i];j--){
con = 1;
memset(mark,0,sizeof(mark));
for(kk=1;kk<=k;kk++){
mark[con] = dp[j][kk];
con++;
mark[con] = dp[j-cost[i]][kk]+val[i];
con++;
}
sort(mark+1,mark+con+1,cmp);
unique(mark,mark+con+1);
for(int t=1;;t++){
if(mark[t] == 0){
for(int q=t+1;q<=66;q++){
mark[q] = 0;
}
break;
}
}
for(kk=1;kk<=k;kk++){
dp[j][kk] = mark[kk];
}
}
}
printf("%d\n",dp[v][k]);
}
}
return 0;
}
原文地址:http://blog.csdn.net/zcr_7/article/details/41324937