#include <stdio.h>
#include <stdlib.h>
struct Fruit {
char name[20];
int weight;
int value;
};
int compare(const void *a, const void *b) {
double ratioA = (double)(((struct Fruit*)a)->value) / (((struct Fruit*)a)->weight);
double ratioB = (double)(((struct Fruit*)b)->value) / (((struct Fruit*)b)->weight);
if (ratioA > ratioB) return -1;
else if (ratioA < ratioB) return 1;
else return 0;
}
double fillBackpack(struct Fruit fruits[], int n, int capacity) {
qsort(fruits, n, sizeof(struct Fruit), compare);
int currentWeight = 0;
double finalValue = 0.0;
printf("装入背包的水果策略:\n");
for (int i = 0; i < n; i++) {
if (currentWeight + fruits[i].weight <= capacity) {
printf("装入 %s\n", fruits[i].name);
currentWeight += fruits[i].weight;
finalValue += fruits[i].value;
} else {
int remainingCapacity = capacity - currentWeight;
finalValue += fruits[i].value * ((double)remainingCapacity / fruits[i].weight);
printf("装入部分 %s\n", fruits[i].name);
break;
}
}
printf("总价值为: %.2f\n", finalValue);
return finalValue;
}
int main() {
struct Fruit fruits[] = {
{"苹果", 5, 10},
{"橙子", 7, 8},
{"香蕉", 4, 7},
{"草莓", 3, 5}
};
int n = sizeof(fruits) / sizeof(fruits[0]);
int capacity = 20;
double maxValue = fillBackpack(fruits, n, capacity);
printf("背包中装入水果的总价值最高为: %.2f\n", maxValue);
return 0;
}