#include <stdio.h>
#include <stdlib.h>
struct Item {
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);
}
int knapsackBranchBound(int W, int wt[], int val[], int n) {
struct Item items[n];
for (int i = 0; i < n; 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;
} else {
int remain = W - currentWeight;
finalValue += items[i].ratio * remain;
break;
}
}
return finalValue;
}
int main() {
int val[] = {60, 100, 120};
int wt[] = {10, 20, 30};
int W = 50;
int n = sizeof(val) / sizeof(val[0]);
double result = knapsackBranchBound(W, wt, val, n);
printf("背包中物品的最大价值为:%.2lf\n", result);
return 0;
}