本文由此博客更改而来,对此博客的解法进行了部分修改,代码结构尚有很多不足之处,敬请原谅~
具体实现请看代码及其注释:
定义的一个节点对象,封装v与w等信息,将被作为二叉树节点使用
class ItemNode implements Comparable<ItemNode>{
int weight;//该节点目前背包中的重量
double value;//该节点目前背包中的总价值
double upprofit;//该节点能够达到的价值上界
int selected; //该节点是否属于左节点(用于最终构造最优解)
int level; //该节点是第几个物品的选择
int index;
ItemNode parent; //该节点的父节点
public int compareTo(ItemNode node){
if(this.upprofit<node.upprofit)
return 1;
else if(this.upprofit == node.upprofit)
return 0;
else
return -1;
}
}
定义算法对象
public class AlgorithmFor01Bag {
int n = 5;
int capacity = 10;
int[] weight = { 2, 6, 4, 1, 5 };
double[] value = { 6, 9, 6, 1, 4