#include <stdio.h>
#include <stdlib.h>
typedef struct {
const char *name;
int weight;
int value;
float costPerformance;
} Fruit;
int compare(const void *f1, const void *f2) {
float cost1 = ((Fruit *)f1)->costPerformance;
float cost2 = ((Fruit *)f2)->costPerformance;
return (cost2 > cost1) - (cost2 < cost1);
}
void fillBackpack(Fruit fruits[], int numFruits, int capacity) {
float totalValue = 0.0;
int i, currentWeight;
for (i = 0; i < numFruits && capacity > 0; i++) {
if (fruits[i].weight <= capacity) {
currentWeight = fruits[i].weight;
capacity -= currentWeight;
} else {
currentWeight = capacity;
capacity = 0;
}
totalValue += fruits[i].costPerformance * currentWeight;
printf("装入 %d 公斤的 %s\n", currentWeight, fruits[i].name);
}
printf("可装入最高总价值: %.2f\n", totalValue);
}
int main() {
Fruit fruits[] = {
{"苹果", 15, 300},
{"香蕉", 18, 180},
{"橘子", 10, 150},
{"猕猴桃", 9, 270}
};
int numFruits = sizeof(fruits) / sizeof(fruits[0]);
int backpackCapacity = 20;
for (int i = 0; i < numFruits; ++i) {
fruits[i].costPerformance = (float)fruits[i].value / fruits[i].weight;
}
qsort(fruits, numFruits, sizeof(Fruit), compare);
fillBackpack(fruits, numFruits, backpackCapacity);
return 0;
}