#include <iostream.h>
#define M 100
#define N 100
int Knapsack(int S[M],int P[M],int C,int n,int V[M][N])
{
for(int p=0;p<=n;p++)
{
V[p][0]=0;
}
for(int q=0;q<=C;q++)
{
V[0][q]=0;
}
for(int i=1;i<=n;i++)
for(int j=1;j<=C;j++)
{
V[i][j]=V[i-1][j];
if(j>=S[i])
{
int a,b;
a=V[i][j];
b=V[i-1][j-S[i]]+P[i];
if(a>=b) { V[i][j]=a; }
else { V[i][j]=b; }
}
}
return V[n][C];
}
void Solution(int S[M],int V[M][N],int C,int n)
{
int j=C;
for(int i=n;i>=0;i--)
{
if(V[i][j]>V[i-1][j])
{
j-=S[i];
S[i]=-1; //若S[i]的值为0,则第i件物品被选中
}
}
}
void main()
{
int n=5;
int C=20;
int V[M][N];
int S[M];
S[1]=1;
S[2]=5;
S[3]=11;
S[4]=6;
S[5]=7;
cout<<"一共有"<<n<<"件物品"<<endl;
cout<<"每件物品的体积是:{"<< S[1]<<","<< S[2]<< ","<<S[3]<<","<< S[4]<<"," <<S[5]<<"}"<<endl;
int P[M];
P[1]=11;
P[2]=15;
P[3]=12;
P[4]=30;
P[5]=5;
cout<<"每件物品的价值是:{"<< P[1]<<","<< P[2]<< ","<<P[3]<<","<< P[4]<<"," <<P[5]<<"}"<<endl;
int value=Knapsack(S,P,C,n,V);
cout<<n<<"件物品在"<<C<<"的容量下能创造的最大价值是:"<<value<<endl;
Solution(S,V,C,n);
cout<<"所选择的物品分别是第:";
for(int k=1;k<=n;k++)
{
if(S[k]==-1)
{
cout<<k<<" ";
}
}
cout<<"件"<<endl;
cout<<"创建的二维数组是:"<<endl;
for(int p=0;p<=n;p++)
{
for(int q=0;q<=C;q++)
{
cout<<V[p][q]<<" ";
}
cout<<endl;
}
}
01背包问题
最新推荐文章于 2022-02-25 21:57:21 发布