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; // 物品价值
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)));
int maxValue = 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) {
queue.add(new Node(node.level + 1, node.weight + weights[node.level],
node.value + values[node.level], bound(node.level + 1, node.weight + weights[node.level])));
}
// 右子树:不选择当前物品
queue.add(new Node(node.level + 1, node.weight, node.value, bound(node.level + 1, node.weight)));
}
}
return maxValue;
}
// 计算上界函数
private int bound(int i, int weight) {
int remainingWeight = capacity - weight; // 剩余重量
int remainingValue = 0; // 剩余价值
for (int j = i; j < n; j++) {
if (weights[j] > remainingWeight) { // 当前物品装不下,跳出循环
break;
}
remainingWeight -= weights[j]; // 减去当前物品的重量
remainingValue += values[j]; // 加上当前物品的价值
}
return remainingValue + (remainingWeight / (double) weights[n - 1]) * values[n - 1]; // 返回上界值,注意这里使用了double类型进行除法运算来保留小数部分的价值
}
}