背包问题指这样一类问题,题意往往可以抽象成:给定一组物品,每种物品都有自己的重量和价格,在限定的总重量内,我们如何选择,才能使得物品的总价格最高。
本文讲的是最基本的01背包问题。
有N件物品和一个容量为V的背包。第i件物品的费用(即体积,下同)是w[i],价值是val[i]。求解将哪些物品装入背包可使这些物品的费用总和不超过背包容量,且价值总和最大。
思路:从左到右
//背包问题:从左往右
//weights 当前货物的重量
//values 当前货物的价值
//index 当前的货号
//alreadyweight 0...index-1 已经做的决定,所形成的目前重量
//bag: 袋子的总重量
//
int process(myvci weights, myvci values, int index, int alreadyweight, int bag)
{
if (alreadyweight > bag)//选的货物超重,无效解
{
return -1;
}
if (index == weights.size()) //无货//重量没超
{
return 0;
}
//1.不要当前的index货物
int p1 = 0 + process(weights, values,index+1, alreadyweight,bag);
//2.要当前货物,后续获得的最大价值
//(当前货物+ 后续得到的价值)
int p2next = process(weights, values, index + 1, alreadyweight + weights[index], bag);
int p2 = 0x7fffffff;
if (p2next != -1)//p2后续无效解
{
p2 = values[index] + p2next;//后续有效
}
//return max(p1,p2);//两个取一个最大来
return p1 > p2 ? p1 : p2;
}
int maxValue1(myvci weights, myvci values, int bag)
{
return process(weights, values, 0, 0, bag);
}
void knapsack_main()
{
cout << "***********01背包问题***********" << endl;
myvci weights;
weights.push_back(3);
weights.push_back(2);
weights.push_back(4);
weights.push_back(7);
myvci values;
values.push_back(5);
values.push_back(6);
values.push_back(3);
values.push_back(9);
int bag = 11;
cout << maxValue1(weights, values, bag) << endl;
}