编辑代码

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

// 豆子结构体,包含价值和重量信息
struct Bean {
    int value;
    int weight;
};

// 比较函数,用于将豆子按照单位重量价值排序
int compare(const void *a, const void *b) {
    double ratioA = ((struct Bean *)a)->value / (double)((struct Bean *)a)->weight;
    double ratioB = ((struct Bean *)b)->value / (double)((struct Bean *)b)->weight;

    return (ratioB > ratioA) - (ratioB < ratioA);
}

// 使用贪心算法解决豆子背包问题
double maxBeans(struct Bean beans[], int n, int capacity) {
    // 按照单位重量价值排序
    qsort(beans, n, sizeof(struct Bean), compare);

    double totalValue = 0.0; // 背包中豆子的总价值

    // 逐个考虑豆子装入背包
    for (int i = 0; i < n; i++) {
        if (capacity >= beans[i].weight) {
            totalValue += beans[i].value;
            capacity -= beans[i].weight;
        } else {
            totalValue += (double)beans[i].value * (capacity / (double)beans[i].weight);
            break; // 背包容量已满,停止装入豆子
        }
    }

    return totalValue;
}

int main() {
    struct Bean beans[] = {{60, 10}, {100, 20}, {120, 30}}; // 每个豆子的价值和重量
    int n = sizeof(beans) / sizeof(beans[0]); // 豆子数量
    int capacity = 50; // 背包容量

    double maxValue = maxBeans(beans, n, capacity);
    printf("背包中豆子的最大值: %.2lf\n", maxValue);

    return 0;
}