0/1背包问题
1. 问题描述
2. 问题分析
代码如下:
#include<iostream>
using namespace std;
//record用来记录0-maxvolume的空间内能容纳的最大价值的物品
int BagProblem(int *volume,int *value,int length,int maxvolume,int *record)
{
int i,j;
for(i = 0; i < length; i++)
{
//注意顺序,如果从volume[i]开始计算最大价值,会导致后面的数据不正确,每轮只是更新当前i种
//物品下在0-maxvolume下所能得到的最大利益
for(j = maxvolume; j >= volume[i]; j--)
{
if(volume[i] <= j)
{
if((record[j - volume[i]] + value[i]) > record[j])
record[j] = record[j - volume[i]] + value[i];
}
}
}
return record[maxvolume];
}
//部分背包问题,贪心算法,其中Goods第一列是物品重量,第二列是物品价值,Goods已经按照(物品价值/物品重量)进行从高到底排序
int PartBagProblem(int Goods[][2],int length,int maxvolume)
{
int i;
int maxvalue = 0;
for(i = 0;i < length;i++)
{
//如果是重量小于可以剩余的容量,则全部要了
if(Goods[i][0] < maxvolume)
{
maxvalue += Goods[i][1];
maxvolume -=Goods[i][0];
}
else
break;
}
if(maxvolume != 0)
{
maxvalue += (maxvolume * Goods[i][1])/ Goods[i][0] ;
}
return maxvalue;
}
int main()
{
int volume[] = {12,16,24,7,29,32,5,43,31,1};
int value[] = {11,16,15,9,24,25,3,32,41,7};
int length = 10;
int record[106] = {0};
cout<<"the max value is "<<BagProblem(volume,value,length,105,record);
int Goods[][2] = {{10,60},{20,100},{30,120}};
cout<<PartBagProblem(Goods,3,50);
return 0;
}