实验目的:分支限界法按广度优先策略遍历问题的解空间树,在遍历过程中,对已经处理的每一个结点根据限界函数估算目标函数的可能取值,从中选取使目标函数取得极值的结点优先进行广度忧先搜索,从而不断调整搜索方向,尽快找到问题的解。因为限界函数常常是基于向题的目标函数而确定的,所以,分支限界法适用于求解最优化问题。本次实验利用分支限界法解决0-1背包问题。?
算法核心思想
详细过程可参考文章:0-1背包问题-分支限界法(优先队列分支限界法)_0-1背包问题-优先队列式分支界限法的基础思想和核心步骤-CSDN博客
解空间树:?
?完整代码:
import java.util.PriorityQueue;
//排列树
class Node implements Comparable<Node> {
int level; // 当前层级
int weight; // 当前重量
int value; // 当前价值
int bound; // 上界
public Node(int level, int weight, int value, int bound) {
this.level = level;
this.weight = weight;
this.value = value;
this.bound = bound;
}
@Override
public int compareTo(Node other) {
// 按照bound的降序排列
return other.bound - this.bound;
}
}
public class Knapsack {
int capacity; // 背包容量
int n; // 物品数量
int[] weights; // 物品重量
int[] values; // 物品价值
int bestvalue;
public Knapsack(int capacity, int n, int[] weights, int[] values) {
this.capacity = capacity;
this.n = n;
this.weights = weights;
this.values = values;
}
public int maxValue() {
// 初始化优先队列
PriorityQueue<Node> queue = new PriorityQueue<>();
queue.add(new Node(0, 0, 0, bound(0, 0,0)));
int maxValue = 0;
this.bestvalue = 0;
while (!queue.isEmpty()) {
Node node = queue.poll(); // 取出队首元素--扩展节点
if (node.level == n) { // 达到叶子节点,更新最大值
maxValue = Math.max(maxValue, node.value);
} else {
// 左子树:选择当前物品
if (node.weight + weights[node.level] <= capacity) {
int leftbound = bound(node.level + 1, node.weight + weights[node.level] ,node.value + values[node.level]);
if(this.bestvalue<node.value + values[node.level]){
this.bestvalue = node.value + values[node.level];
}
if (leftbound<this.bestvalue){
continue;
}
queue.add(new Node(node.level + 1, node.weight + weights[node.level],
node.value + values[node.level],leftbound));
}
// 右子树:不选择当前物品
int rightbound =bound(node.level + 1, node.weight,node.value);
if (rightbound<this.bestvalue){
continue;
}
queue.add(new Node(node.level + 1, node.weight, node.value,rightbound));
}
}
return maxValue;
}
// 计算上界函数
private int bound(int i, int weight,int val) {
int remainingWeight = capacity - weight; // 剩余重量
int remainingValue = 0; // 剩余价值
int j = i;
for (; j < n; j++) {
if (weights[j] > remainingWeight) { // 当前物品装不下,跳出循环
break;
}
remainingWeight -= weights[j]; // 减去当前物品的重量
remainingValue += values[j]; // 加上当前物品的价值
}
if (j<n){ //使用了double类型进行除法运算来保留小数部分的价值
remainingValue = (int) (remainingValue + remainingWeight*(double)(values[j]/weights[j]));
}
return remainingValue+val;
}
public static void main(String[] args) {
//int[] wt = {4,7,5,3};
//int[] val = {40,42,25,12};
//必须按照单位单位价值从大到小
int[] wt = {4,1,1,2,12};
int[] val = {10,2,1,2,4};
int capacity = 15;
int n = wt.length;
Knapsack knapsack = new Knapsack(capacity,n,wt,val);
int res = knapsack.maxValue();
System.out.println(res);
}
}
输出结果:15