public class Knapsack {
private static final int MAX_VALUE = 100;
private static final int MAX_WEIGHT = 50;
private static final int ITEM_COUNT = 3;
public static void main(String[] args) {
int[][] items = {
{3, 4, 5},
{2, 3, 2},
{4, 5, 1}
};
int capacity = 10;
System.out.println("背包容量:" + capacity);
System.out.println("物品信息:");
printItems(items);
System.out.println("最优解:" + branchAndBound(items, capacity));
}
private static int branchAndBound(int[][] items, int capacity) {
int maxValue = 0;
int bound = calculateBound(items);
if (bound <= capacity) {
maxValue = calculateValue(items, capacity);
}
return maxValue;
}
private static int calculateBound(int[][] items) {
int totalWeight = 0;
int totalValue = 0;
for (int[] item : items) {
totalWeight += item[0];
totalValue += item[1];
}
int maxWeight = getMaxWeight(items);
int bound = totalValue - (totalWeight - maxWeight) * (maxWeight - totalWeight + 1) / (totalWeight - maxWeight);
return bound;
}
private static int getMaxWeight(int[][] items) {
int maxWeight = Integer.MIN_VALUE;
for (int[] item : items) {
maxWeight = Math.max(maxWeight, item[0]);
}
return maxWeight;
}
private static int calculateValue(int[][] items, int capacity) {
int maxValue = Integer.MIN_VALUE;
for (int i = 0; i <= ITEM_COUNT; i++) {
for (int j = 0; j < items.length; j++) {
if (i == 0 || j == ITEM_COUNT) {
continue;
}
if (items[j][0] <= capacity) {
capacity -= items[j][0];
int value = calculateValue(items, capacity);
capacity += items[j][0];
maxValue = Math.max(maxValue, value);
} else {
capacity += items[j][0];
}
}
}
return maxValue;
}
private static void printItems(int[][] items) {
for (int[] item : items) {
System.out.println("物品:" + item[2] + ",重量:" + item[0] + ",价值:" + item[1]);
}
}
}