#include <stdio.h>
#define MAX_N 100
typedef struct {
int weight;
int value;
} Item;
int maxProfit;
int bestSolution[MAX_N];
int currentSolution[MAX_N];
int bound(Item items[], int n, int capacity, int level, int weight, int value) {
int boundValue = value;
int totalWeight = weight;
for (int i = level; i < n; i++) {
if (totalWeight + items[i].weight <= capacity) {
totalWeight += items[i].weight;
boundValue += items[i].value;
} else {
boundValue += (capacity - totalWeight) * items[i].value / items[i].weight;
break;
}
}
return boundValue;
}
void knapsack(Item items[], int n, int capacity, int level, int weight, int value) {
if (level == n) {
if (value > maxProfit) {
maxProfit = value;
for (int i = 0; i < n; i++) {
bestSolution[i] = currentSolution[i];
}
}
return;
}
int upperBound = bound(items, n, capacity, level, weight, value);
if (upperBound <= maxProfit) {
return;
}
knapsack(items, n, capacity, level + 1, weight, value);
if (weight + items[level].weight <= capacity) {
currentSolution[level] = 1;
knapsack(items, n, capacity, level + 1, weight + items[level].weight, value + items[level].value);
currentSolution[level] = 0;
}
}
int main() {
int n;
int capacity;
Item items[MAX_N];
printf("请输入物品数量:");
scanf("%d", &n);
printf("请输入背包容量:");
scanf("%d", &capacity);
printf("请依次输入每个物品的重量和价值:\n");
for (int i = 0; i < n; i++) {
printf("物品 %d:", i + 1);
scanf("%d%d", &items[i].weight, &items[i].value);
}
maxProfit = 0;
knapsack(items, n, capacity, 0, 0, 0);
printf("最大总价值:%d\n", maxProfit);
printf("最佳解决方案:");
for (int i = 0; i < n; i++) {
printf("%d ", bestSolution[i]);
}
printf("\n");
return 0;
}