背包问题

//背包问题-动态规划(分解与递推)
#include "stdafx.h"
#include "Knapsack.h"
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

//0-1背包问题,物品=1
int Knapsack_0_1_Problem(const int* pWeight, const int* pValue, int count, int totalweight)
{
	vector<int> resultVec(totalweight+1, 0); //前面加多一个无素,作为边界使用
	for (int i = 0; i < count; i++)
	{
		for (int j = totalweight; j >= pWeight[i]; j--) //逆序
		{//如果背包可以放得下,则计算max(不放当前物体的最大价值,减去相当前物体的重量求剩余背包的最大价值+当前物体的价值)
			resultVec[j] = max(resultVec[j], resultVec[j-pWeight[i]]+pValue[i]);
		}

		for (int j = 1; j <= totalweight; j++)
			cout<<setw(3)<<resultVec[j];
		cout<<endl;
	}

	return resultVec[totalweight];
}

//完全背包问题,物品>=0
int Knapsack_Complete_Problem(const int* pWeight, const int* pValue, int count, int totalweight)
{
	vector<int> resultVec(totalweight+1, 0); //前面加多一个无素,作为边界使用
	for (int i = 0; i < count; i++)
	{
		for (int j = pWeight[i]; j <= totalweight; j++) //顺序,物品叠加
		{//如果背包可以放得下,则计算max(不放当前物体的最大价值,减去相当前物体的重量求剩余背包的最大价值+当前物体的价值)
			resultVec[j] = max(resultVec[j], resultVec[j-pWeight[i]]+pValue[i]);
		}

		for (int j = 1; j <= totalweight; j++)
			cout<<setw(3)<<resultVec[j];
		cout<<endl;
	}

	return resultVec[totalweight];
}

//多重背包问题,物品>=0且<=k
int Knapsack_Multiple_Problem(const int* pWeight, const int* pValue, const int *pNumber, int count, int totalweight)
{
	vector<int> resultVec(totalweight+1, 0); //前面加多一个无素,作为边界使用
	for (int i = 0; i < count; i++)
	{
		if (pNumber[i]*pWeight[i] >= totalweight) //如果件数足够,则用完全背包
		{
			for (int j = pWeight[i]; j <= totalweight; j++) //顺序,物品叠加
			{//如果背包可以放得下,则计算max(不放当前物体的最大价值,减去相当前物体的重量求剩余背包的最大价值+当前物体的价值)
				resultVec[j] = max(resultVec[j], resultVec[j-pWeight[i]]+pValue[i]);
			}
		}
		else
		{
			int c = pNumber[i];
			for (int k = 1; k <= c; c -= k, k *= 2) //二进制优化,每次移动2^k直至不可移动
			{
				for (int j = totalweight; j >= pWeight[i]*k; j--) //逆序
					resultVec[j] = max(resultVec[j], resultVec[j-pWeight[i]*k]+pValue[i]*k);
			}

			if (c >0) //余数再来计算一次
			{
				for (int j = totalweight; j >= pWeight[i]*c; j--) //逆序
					resultVec[j] = max(resultVec[j], resultVec[j-pWeight[i]*c]+pValue[i]*c);
			}
		}

		for (int j = 1; j <= totalweight; j++)
			cout<<setw(3)<<resultVec[j];
		cout<<endl;
	}

	return resultVec[totalweight];
}

void KnapsackTest()
{
	const int pWeight[] = {1 , 3 , 2 , 6 , 2}; 
	const int pValue[]  = {2, 5 , 3 , 10 , 4};  
	const int pNumber[]  = {6, 2 , 3 , 4 , 2};  
	const int count = sizeof(pWeight)/sizeof(pWeight[0]);
	cout<<"01背包问题,物品=1"<<endl;
	Knapsack_0_1_Problem(pWeight, pValue, count, 12);
	cout<<"完全背包问题,物品>=0"<<endl;
	Knapsack_Complete_Problem(pWeight, pValue, count, 12);
	cout<<"多重背包问题,物品>=0且<=k"<<endl;
	Knapsack_Multiple_Problem(pWeight, pValue, pNumber, count, 12);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值