#include <stdio.h>
#include <stdlib.h>
typedef struct {
const char *name;
double weight;
double value;
double value_per_kg;
} Fruit;
int compare(const void *a, const void *b) {
Fruit *fruit1 = (Fruit *)a;
Fruit *fruit2 = (Fruit *)b;
if (fruit1->value_per_kg > fruit2->value_per_kg) return -1;
if (fruit1->value_per_kg < fruit2->value_per_kg) return 1;
return 0;
}
void fill_knapsack(Fruit fruits[], int size, double capacity) {
double total_value = 0.0;
printf("装入策略如下:\n");
for (int i = 0; i < size; i++) {
if (capacity == 0) break;
if (fruits[i].weight <= capacity) {
capacity -= fruits[i].weight;
total_value += fruits[i].value;
printf("%s: %.2f kg\n", fruits[i].name, fruits[i].weight);
} else {
double part = capacity / fruits[i].weight;
total_value += fruits[i].value * part;
printf("%s: %.2f kg\n", fruits[i].name, capacity);
capacity = 0;
}
}
printf("背包中水果的总价值为:%.2f 元\n", total_value);
}
int main() {
Fruit fruits[] = {
{"苹果", 15, 300},
{"香蕉", 18, 180},
{"橘子", 10, 150},
{"猕猴桃", 9, 270}
};
const int size = sizeof(fruits) / sizeof(fruits[0]);
for (int i = 0; i < size; i++) {
fruits[i].value_per_kg = fruits[i].value / fruits[i].weight;
}
qsort(fruits, size, sizeof(Fruit), compare);
double capacity = 20;
fill_knapsack(fruits, size, capacity);
return 0;
}