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