编辑代码

#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;
}