#include <stdio.h>
#include <stdlib.h>
struct Bean {
int value;
int weight;
};
int compare(const void *a, const void *b) {
double ratioA = ((struct Bean *)a)->value / (double)((struct Bean *)a)->weight;
double ratioB = ((struct Bean *)b)->value / (double)((struct Bean *)b)->weight;
return (ratioB > ratioA) - (ratioB < ratioA);
}
double maxBeans(struct Bean beans[], int n, int capacity) {
qsort(beans, n, sizeof(struct Bean), compare);
double totalValue = 0.0;
for (int i = 0; i < n; i++) {
if (capacity >= beans[i].weight) {
totalValue += beans[i].value;
capacity -= beans[i].weight;
} else {
totalValue += (double)beans[i].value * (capacity / (double)beans[i].weight);
break;
}
}
return totalValue;
}
int main() {
struct Bean beans[] = {{60, 10}, {100, 20}, {120, 30}};
int n = sizeof(beans) / sizeof(beans[0]);
int capacity = 50;
double maxValue = maxBeans(beans, n, capacity);
printf("背包中豆子的最大值: %.2lf\n", maxValue);
return 0;
}