高手请进:0-1背包问题,结果不对,急!!!
本人用的是动态规划方法,状态方程为:
w>=wi时:c[i][w]=max{v[i]+c[i-1][w-wi],c[i-1][w]};
w<wi时:c[i][w]=c[i-1][w];
i=0 or w=0时,c[i][w]=0;
代码如下;
//0-1knapsack problem#include<stdio.h>int WEIGHT=1000; //背包承重上限const int T=5; //物品数量static int c[6][1001]; //动态表void KNAPSACK(int [],int [],int ,int [][1001]); //动态规划void PRINT_KNAPSACK(int [],int b[][1001],int ,int ,int []);//打印结果void main(){ int v1[T] = {8,10,4,5,5}; //value int w1[T] = {600,400,200,200,300}; //weight int v[6],w[6],b[6][1001]; for(int i=0;i<T;i++) { v[i+1]=v1[i]; //1 to T w[i+1]=w1[i]; } KNAPSACK(v,w,T+1,b); PRINT_KNAPSACK(v,b,WEIGHT,T,w);}void KNAPSACK(int v[],int w[],int len,int b[][1001]){ int i,W; for(i=1;i<len;i++) //1 to T { for(W=1;W<=WEIGHT;W++) { if(w[i]<=W) { if(v[i]+c[i-1][W-w[i]]>c[i-1][W]) { c[i][W]=c[i][W-w[i]]+v[i]; b[i][W]=1; //存储要选择的物品序号 } else { c[i][W]=c[i-1][W]; b[i][W]=0; } } else //w[i]>W { c[i][W]=c[i-1][W]; b[i][W]=0; //需丢弃的物品序号 } }//for W }//for i}//打印结果void PRINT_KNAPSACK(int v[],int b[][1001],int W,int i,int w[]){ if(i==0||WEIGHT==0) return; if(b[i][W]==1) { PRINT_KNAPSACK(v,b,W-w[i],i-1,w); printf("%d\t%d\n",w[i],v[i]); } else { PRINT_KNAPSACK(v,b,W,i-1,w); }}