1 # include <stdio.h> 2 # include <stdlib.h> 3 # include <string.h> 4 # define max(x,y) x>y?x:y; 5 int v[1001];//价值 6 int w[1001];//重量 7 int dp[1001][1001]; 8 int main() 9 { 10 int n,m; 11 while(scanf("%d%d",&m,&n)!=EOF) 12 { 13 memset(dp,0,sizeof(dp));//初始化 14 for(int i=1; i<=n; i++) 15 scanf("%d%d",&w[i],&v[i]); 16 for(int i=1; i<=n; i++) // 物品数 17 for(int j=m; j>=w[i]; j--) //放入背包 18 dp[i][j]=max(dp[i-1][j],dp[i-1][j-w[i]]+v[i]);// 与前面对比 19 printf("%d ",dp[n][m]); 20 } 21 } 22 23 //01背包第K优解问题 24 struct pack 25 { 26 int v;//体积 27 int w;//价值 28 }node[length]; 29 30 for(i = 0;i<n;i++) 31 { 32 for(j = v;j>=node[i].v;j--) 33 { 34 for(d = 1;d<=k;d++) 35 { 36 a[d] = dp[j-node[i].v][d] + node[i].w; 37 b[d] = dp[j][d]; 38 } 39 x = y = z = 1; 40 a[d] = b[d] = -1; 41 while(z<=k && (x<=k || y<=k)) 42 { 43 if(a[x]>b[y]) 44 dp[j][z] = a[x++]; 45 else 46 dp[j][x] = b[y++]; 47 if(dp[j][z]!=dp[j][z-1]) 48 z++; 49 } 50 } 51 } 52 //dp[v][k]为第K优解,例题:HDU2639