问题描述:
给定n种物品和一背包。物品i的重量是wi,其价值为vi,背包的容量为C。问:应如何选择装入背包的物品,使得装入背包中物品的总价值最大?
算法设计分析:
和回溯法中的界定函数类似,对每一个活动节点N,计算收益的上限maxPossibleProfitInSubtree
,使得以N为根的子树中,任何一个节点的收益都不可能超过这个值。
活动节点使用大根堆maxHeap<heapNode>
,按需构造解空间树——子集树。
大根堆元素heapNode结构:
upperProfit //以该节点为根的子树中任一节点的收益上限
profit //该节点目前的收益值
weight //该节点目前的重量
level //该节点在解空间树的层数
liveNode //指向解空间树的节点(树的节点数据成员包括:
// 指向父节点的parent指针和布尔类型leftChild,当且仅当此节点是左孩子时为true)
节点按其upperProfit
值从大根堆中取出。
算法步骤:
1、将背包装载对象按收益密度递增顺序排序;
2、检查左孩子节点,若左孩子可行(左孩子的目前重量小于总的capacity),向大根堆中添加此节点;
3、检查右孩子节点,当且仅当右孩子的maxPossibleProfitInSubtree值大于目前的最大收益时,右孩子可行,将右孩子加入大根堆;
4、从大根堆中取出一个新元素(upperProfit值最大的节点),重复2、3步骤直到最后一层节点;
5、沿着最后一个节点到根节点路径构造最佳0/1背包解。
例如:0/1背包问题,当n=3时,w={20,15,15}, p={40,25,25}, c=30。收益密度{2, 5/3, 5/3}。大根堆分支界定法:收益大的优先。
队列中的元素:{}—>{A}—>{B,C}—>{C,D,E}—>{C,E}—>{C,J,K}—>{C}—>{F,G}—>{G,L,M}—>{G,M}—>{G}—>{N,O}—>{O}—>{}
C++实现
解空间树的节点结构:
struct bbNode
{
// data members
bbNode* parent; // pointer to parent node
bool leftChild; // true iff left child of parent
// constructor
bbNode(bbNode* theParent, bool theLeftChild)
{
parent = theParent;
leftChild = theLeftChild;
}
};
大根堆的元素类型:
struct heapNode
{
// data members
bbNode* liveNode;
double upperProfit;
double profit;
double weight;
int upperWeight; // upper weight of live node
int level; // level of live node
// constructors
heapNode() {};
heapNode(bbNode* theLiveNode, double theUpperProfit,
double theProfit, double theWeight, int theLevel)
{
liveNode = theLiveNode;
upperProfit = theUpperProfit;
profit = theProfit;
weight = theWeight;
level = theLevel;
}
operator<(const heapNode right)
{
return upperProfit < right.upperProfit;}
// type conversion to enable arithmetics etc.
operator double() {
return upperProfit;}
};
算法程序:
// global variables
double capacity;
int numberOfObjects;
double *weight;
double *profit;
double weightOfCurrentPacking;
double profitFromCurrentPacking;
int *bestPackingSoFar;
maxHeap<heapNode> liveNodeMaxHeap;
double maxProfitBBKnapsack()
{
// Max-profit branch-and-bound search of solution space tree.