直接遍历每一种情况,用数组maxV[i]表示第i个物品放不放进去,0不放进,1放进。
#include<iostream>
using namespace std;
int main()
{
int w[5]={2,2,6,5,4},v[5]={6,3,5,4,6}; //重量和价值
int n=5,c=10; //n物品个数 ,c背包容量
int max=0; //每轮最大价值
int max1=0; //最终最大价值
int weight=0;
int weight1=0;
for(int i=0;i<pow((double)2,(double)n);i++) //遍历每一种情况
{
int maxV[5]={0}; //物品是否放进,1放进,0不放
int temp =i;
for(int j=0; j<n; j++)
{
if (temp%2 != 0)
maxV[j]=1;
temp=temp/2;
}
cout<<"第"<<i+1<<"种情况:"<<endl;
for(int i=0;i<5;i++)
{
cout<<maxV[i]<<" ";
max += v[i]*maxV[i];
weight+=w[i]*maxV[i];
}
cout<<endl<<"最大价值是:"<<max<<endl;
cout<<"重量是:"<<weight<<endl<<endl;
if(weight<= c && max >max1)
{
max1=max;
weight1=weight;
}
max=0;
weight=0;
}
cout<<endl<<endl<<"最大价值是:"<<max1<<endl;
return 0;
}