#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Item {
char name[50];
int value;
int weight;
double ratio;
};
int compare(const void *a, const void *b) {
double ratioA = ((struct Item *)a)->ratio;
double ratioB = ((struct Item *)b)->ratio;
return (ratioB > ratioA) - (ratioB < ratioA);
}
double knapsackBranchBound(int W, int wt[], int val[], char names[][50], int n) {
struct Item items[n];
for (int i = 0; i < n; i++) {
strcpy(items[i].name, names[i]);
items[i].value = val[i];
items[i].weight = wt[i];
items[i].ratio = (double)val[i] / wt[i];
}
qsort(items, n, sizeof(items[0]), compare);
int currentWeight = 0;
double finalValue = 0.0;
for (int i = 0; i < n; i++) {
if (currentWeight + items[i].weight <= W) {
currentWeight += items[i].weight;
finalValue += items[i].value;
printf("将 %s 放入背包\n", items[i].name);
} else {
int remain = W - currentWeight;
finalValue += items[i].ratio * remain;
printf("将 %s 的部分放入背包\n", items[i].name);
break;
}
}
return finalValue;
}
int main() {
char names[][50] = {"苹果", "雪梨", "香蕉"};
int val[] = {50, 60, 70};
int wt[] = {20, 50, 30};
int W = 50;
int n = sizeof(val) / sizeof(val[0]);
double result = knapsackBranchBound(W, wt, val, names, n);
printf("背包中物品的最大价值为:%.2lf\n", result);
return 0;
}