#include <stdio.h>
#include <stdlib.h>
#define MAX_ITEMS 100
typedef struct {
int weight;
int value;
} Item;
typedef struct {
int level;
int profit;
int weight;
double bound;
} Node;
int compareNodes(const void *a, const void *b) {
return ((Node *)a)->bound - ((Node *)b)->bound;
}
double calculateBound(Node node, int numItems, int capacity, Item items[]) {
int j, k;
double bound = node.profit;
int totalWeight = node.weight;
if (node.weight >= capacity) {
return 0;
}
for (j = node.level + 1; j < numItems; j++) {
if (totalWeight + items[j].weight <= capacity) {
bound += items[j].value;
totalWeight += items[j].weight;
} else {
k = j;
break;
}
}
if (k < numItems) {
bound += (capacity - totalWeight) * items[k].value / (double)items[k].weight;
}
return bound;
}
int branchAndBound(Item items[], int numItems, int capacity) {
Node *priorityQueue = (Node *)malloc(sizeof(Node) * MAX_ITEMS * 2);
int queueSize = 0;
Node root = {0, 0, 0, 0};
root.bound = calculateBound(root, numItems, capacity, items);
priorityQueue[queueSize++] = root;
int maxProfit = 0;
while (queueSize > 0) {
Node currentNode = priorityQueue[--queueSize];
if (currentNode.bound > maxProfit) {
Node leftChild = {currentNode.level + 1,
currentNode.profit + items[currentNode.level + 1].value,
currentNode.weight + items[currentNode.level + 1].weight,
0};
leftChild.bound = calculateBound(leftChild, numItems, capacity, items);
if (leftChild.weight <= capacity && leftChild.profit > maxProfit) {
maxProfit = leftChild.profit;
}
if (leftChild.bound > maxProfit) {
priorityQueue[queueSize++] = leftChild;
}
Node rightChild = {currentNode.level + 1,
currentNode.profit,
currentNode.weight,
0};
rightChild.bound = calculateBound(rightChild, numItems, capacity, items);
if (rightChild.weight <= capacity && rightChild.profit > maxProfit) {
maxProfit = rightChild.profit;
}
if (rightChild.bound > maxProfit) {
priorityQueue[queueSize++] = rightChild;
}
}
}
free(priorityQueue);
return maxProfit;
}
int main() {
Item items[] = {{2, 5}, {3, 8}, {5, 12}};
int numItems = sizeof(items) / sizeof(items[0]);
int capacity = 5;
int result = branchAndBound(items, numItems, capacity);
printf("最大总价值: %d\n", result);
return 0;
}