//背包问题-动态规划(分解与递推)
#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);
}
背包问题
最新推荐文章于 2022-05-21 18:01:16 发布