#include <stdio.h>
#include <stdlib.h>
#define N 100
typedef struct {
int level;
int profit;
int weight;
float bound;
} Node;
typedef struct {
int index;
float bound;
} QueueElement;
int compare(const void *a, const void *b) {
float diff = ((QueueElement *)a)->bound - ((QueueElement *)b)->bound;
return (diff > 0) ? 1 : ((diff < 0) ? -1 : 0);
}
void heapifyUp(QueueElement *queue, int index) {
while (index > 0) {
int parent = (index - 1) / 2;
if (queue[index].bound < queue[parent].bound) {
QueueElement temp = queue[index];
queue[index] = queue[parent];
queue[parent] = temp;
index = parent;
} else {
break;
}
}
}
int knapsackBranchBound(int values[], int weights[], int n, int capacity) {
Node root = { .level = -1, .profit = 0, .weight = 0, .bound = 0 };
int maxProfit = 0;
QueueElement *queue = (QueueElement *)malloc(sizeof(QueueElement) * n);
int rear = -1;
queue[++rear] = (QueueElement){ .index = -1, .bound = root.bound };
while (rear != -1) {
QueueElement current = queue[0];
rear--;
queue[0] = queue[rear + 1];
int index = 0;
while (1) {
int leftChild = 2 * index + 1;
int rightChild = 2 * index + 2;
int minIndex = index;
if (leftChild <= rear && queue[leftChild].bound < queue[minIndex].bound) {
minIndex = leftChild;
}
if (rightChild <= rear && queue[rightChild].bound < queue[minIndex].bound) {
minIndex = rightChild;
}
if (minIndex != index) {
QueueElement temp = queue[index];
queue[index] = queue[minIndex];
queue[minIndex] = temp;
index = minIndex;
} else {
break;
}
}
int i = current.index + 1;
Node next;
next.level = root.level + 1;
next.weight = root.weight + weights[i];
next.profit = root.profit + values[i];
if (next.weight <= capacity && next.profit > maxProfit) {
maxProfit = next.profit;
}
next.bound = (float)next.profit + (float)(capacity - next.weight) * values[i] / weights[i];
if (next.bound > maxProfit && next.level < n - 1) {
queue[++rear] = (QueueElement){ .index = i, .bound = next.bound };
heapifyUp(queue, rear);
}
next.weight = root.weight;
next.profit = root.profit;
next.bound = (float)next.profit + (float)(capacity - next.weight) * values[i] / weights[i];
if (next.bound > maxProfit && next.level < n - 1) {
queue[++rear] = (QueueElement){ .index = i, .bound = next.bound };
heapifyUp(queue, rear);
}
}
free(queue);
return N;
}
int main() {
int values[] = {60, 100, 120};
int weights[] = {10, 20, 30};
int n = sizeof(values) / sizeof(values[0]);
int capacity = 50;
int result = knapsackBranchBound(values, weights, n, capacity);
printf("最大值 = %d\n", result);
return 0;
}