标签:
代码1:
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 const int MIN=0x80000000; 5 const int N=3; //物品数量 6 const int V=5; //背包容量 7 int f[N+1][V+1]; 8 9 int Package(int *W,int *C,int N,int V); 10 void main(int argc,char *argv[]) 11 { 12 int W[4]={0,7,5,8}; //物品权重 13 int C[4]={0,2,3,4}; //物品大小 14 int result=Package(W,C,N,V); 15 if(result>0) 16 { 17 cout<<endl; 18 cout<<"the opt value:"<<result<<endl; 19 int i=N,j=V; 20 while(i) 21 { 22 if(f[i][j]==(f[i-1][j-C[i]]+W[i])) 23 { 24 cout<<i<<":"<<"w="<<W[i]<<",c="<<C[i]<<endl; 25 j-=C[i]; 26 } 27 i--; 28 } 29 } 30 else 31 cout<<"can not find the opt value"<<endl; 32 return; 33 } 34 35 int Package(int *W,int *C,int N,int V) 36 { 37 int i,j; 38 memset(f,0,sizeof(f)); //初始化为0 39 40 for(i=0;i<=N;i++) 41 for(j=1;j<=V;j++) //此步骤是解决是否恰好满足背包容量, 42 f[i][j]=MIN; //若“恰好”满足背包容量,即正好装满背包,则加上此步骤,若不需要“恰好”,则初始化为0 43 44 for(i=1;i<=N;i++) 45 for(j=C[i];j<=V;j++) 46 { 47 f[i][j]=(f[i-1][j]>f[i-1][j-C[i]]+W[i])?f[i-1][j]:(f[i-1][j-C[i]]+W[i]); 48 cout<<"f["<<i<<"]["<<j<<"]="<<f[i][j]<<endl; 49 } 50 return f[N][V]; 51 }
代码2:
1 代码2 2 3 #include <iostream> 4 #include <vector> 5 using namespace std; 6 const int MIN=0x80000000; 7 const int N=3; //物品数量 8 const int V=5; //背包容量 9 int f[V+1]; 10 11 int Package(int *W,int *C,int N,int V); 12 void main(int argc,char *argv[]) 13 { 14 int W[4]={0,7,5,8}; //物品权重 15 int C[4]={0,2,3,4}; //物品大小 16 int result=Package(W,C,N,V); 17 if(result>0) 18 { 19 cout<<endl; 20 cout<<"the opt value:"<<result<<endl; 21 } 22 else 23 cout<<"can not find the opt value"<<endl; 24 return; 25 } 26 27 int Package(int *W,int *C,int N,int V) 28 { 29 int i,j; 30 memset(f,0,sizeof(f)); //初始化为0 31 32 for(i=1;i<=V;i++) //此步骤是解决是否恰好满足背包容量, 33 f[i]=MIN; //若“恰好”满足背包容量,即正好装满背包,则加上此步骤,若不需要“恰好”,则初始化为0 34 35 for(i=1;i<=N;i++) 36 for(j=V;j>=C[i];j--) //注意此处与解法一是顺序不同的,弄清原因 37 { 38 f[j]=(f[j]>f[j-C[i]]+W[i])?f[j]:(f[j-C[i]]+W[i]); 39 cout<<"f["<<i<<"]["<<j<<"]="<<f[j]<<endl; 40 } 41 return f[V]; 42 }
标签:
原文地址:http://www.cnblogs.com/david-wang/p/4340258.html