#include<iostream>
#include<vector>
using namespace std;
int goodsSum;
int capacityKnapsack;
int bestValue = INT_MIN;
vector<int>* goodsWeight;
vector<int>* goodsValue;
vector<bool> bestPut;
void backTrack(int depth, int weightKnapsack, int valueKnapsack, vector<bool> put);
int main()
{
cout<<"请输入物品的数量:";
cin>>goodsSum;
cout<<"请输入背包的容量:";
cin>>capacityKnapsack;
cout<<"请依次输入 "<<goodsSum<<" 个物品对应的重量与价值:";
goodsWeight = new vector<int>(goodsSum);
goodsValue = new vector<int>(goodsSum);
cout<<(*goodsWeight).size();
vector<bool> tempPut(goodsSum);
for (int i = 0; i < goodsSum; i++)
{
cin>>(*goodsWeight)[i]>>(*goodsValue)[i];
}
backTrack(0, 0, 0, tempPut);
cout<<endl<<"装入背包中的总价值最大为:"<<bestValue<<endl;
cout<<"要使得总价值最大,放入背包的物品应为:"<<endl;
for (int i = 0; i < goodsSum; i++)
{
if (bestPut[i]){
cout<<"物品"<<i + 1<<" ";
}
}
cout<<endl;
return 0;
}
void backTrack(int depth, int weightKnapsack, int valueKnapsack, vector<bool> put)
{
if (depth == goodsSum){
if (valueKnapsack > bestValue){
bestValue = valueKnapsack;
bestPut.swap(put);
}
}
else{
put[depth] = false;
backTrack(depth + 1, weightKnapsack, valueKnapsack, put);
put[depth] = true;
if (weightKnapsack + (*goodsWeight)[depth] <= capacityKnapsack){
weightKnapsack += (*goodsWeight)[depth];
valueKnapsack += (*goodsValue)[depth];
backTrack(depth + 1, weightKnapsack, valueKnapsack, put);
}
}
}
/*
输入样例:
5
10
2 6
2 3
6 5
5 4
4 6
输出样例:
装入背包中的总价值最大为:15
要使得总价值最大,放入背包的物品应为:
物品1 物品2 物品5
*/
05-18
06-18
1万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)