#include <iostream>
using namespace std;
#define N 6
int w[N]={6,5,4,2,1};
int v[N]={5,3,5,3,2};
int x[N];
int n=5;
int c=10;
int SumWeight = 0;
int SumValue = 0;
int OptimalValue = 0;
int OptimalSolution[N];
void backtracking(int t)
{
if(t>n)
{
if(SumValue>OptimalValue)
{
OptimalValue = SumValue;
for(int i=1; i<=n; ++i)
OptimalSolution[i] = x[i];
}
}
else
{
for(int i=0; i<=1; ++i)
{
x[t]=i;
if(i==0)
{
backtracking(t+1);
}
else
{
if((SumWeight+w[t])<=c)
{
SumWeight += w[t];
SumValue += v[t];
backtracking(t+1);
SumWeight -= w[t];
SumValue -= v[t];
}
}
}
}
}
int main()
{
cout<<"请输入物品的个数:"<<n<<endl;
cout<<"请输入每个物品的重量:"<<w[0]<<" "<<w[1]<<" "<<w[2]<<" "<<w[3]<<" "<<w[4]<<endl;
cout<<"请输入每个物品的价值:"<<v[0]<<" "<<v[1]<<" "<<v[2]<<" "<<v[3]<<" "<<v[4]<<endl;
cout<<"请输入背包的限制容量:"<<c<<endl;
backtracking(1);
cout<<"最优价值是:"<<OptimalValue<<endl;
cout<<"(";
for(int i=1;i<=n;i++)
cout<<OptimalSolution[i]<<" ";
cout<<")";
return 0;
}