0-1 背包问题 回溯法

#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
*/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值