编辑代码

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int weight;
    int value;
    double valuePerWeight; // 单位价值
} Bean;

int compare(const void *a, const void *b) {
    double diff = ((Bean *)b)->valuePerWeight - ((Bean *)a)->valuePerWeight;
    if (diff > 0) return 1;
    if (diff < 0) return -1;
    return 0;
}

double maxBeanValue(Bean beans[], int num_beans, int knapsack_capacity) {
    qsort(beans, num_beans, sizeof(Bean), compare);

    double totalValue = 0;
    int currentWeight = 0;

    for (int i = 0; i < num_beans; i++) {
        if (currentWeight + beans[i].weight <= knapsack_capacity) {
            totalValue += beans[i].value;
            currentWeight += beans[i].weight;
        }
    }

    return totalValue;
}

int main() {
    Bean beans[] = {{5, 10, 2.0}, {8, 12, 1.5}, {4, 7, 1.75}};
    int num_beans = sizeof(beans) / sizeof(beans[0]);
    int knapsack_capacity = 10;

    double result = maxBeanValue(beans, num_beans, knapsack_capacity);

    printf("最大豆子价值: %.2f\n", result);

    return 0;
}