编辑代码

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

// 定义豆子的结构体
typedef struct {
    int weight;  // 豆子的重量
    int value;   // 豆子的价值
} Bean;

// 比较函数,用于排序豆子
int compare(const void *a, const void *b) {
    double r1 = ((Bean *)b)->value / (double)((Bean *)b)->weight;
    double r2 = ((Bean *)a)->value / (double)((Bean *)a)->weight;
    return r1 - r2;
}

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

    double totalValue = 0.0;  // 记录背包中豆子的总价值
    int i;

    for (i = 0; i < n; i++) {
        if (capacity >= beans[i].weight) {
            totalValue += beans[i].value;
            capacity -= beans[i].weight;
        } else {
            totalValue += beans[i].value * (capacity / (double)beans[i].weight);
            break;
        }
    }

    return totalValue;
}

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

    double result = maxBeanValue(beans, n, capacity);

    printf("背包中豆子的最大总价值为: %.2f\n", result);

    return 0;
}