编辑代码

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

// 豆子结构体
struct Bean {
    int weight;                 // 重量
    int value;                  // 价值
    double value_weight_ratio;  // 价值重量比
};

int beanBag(int capacity, vector<Bean>& beans) {
    // 计算每个豆子的价值重量比,并按照比值从大到小排序
    for (auto bean : beans) {
        bean.value_weight_ratio = (double)bean.value / bean.weight;
    }
    sort(beans.begin(), beans.end(), [](const Bean& a, const Bean& b) {
        return a.value_weight_ratio > b.value_weight_ratio;
    });

    int totalValue = 0;  // 总价值
    // 遍历豆子列表,将豆子放入背包
    for (auto bean : beans) {
        if (capacity >= bean.weight) {
            totalValue += bean.value;
            capacity -= bean.weight;
        }
    }
    return totalValue;
}

int main() {
    int capacity = 20;  // 背包容量
    vector<Bean> beans = {{5, 10}, {10, 20}, {15, 30}, {8, 15}, {4, 7}};
    int maxTotalValue = beanBag(capacity, beans);
    cout << "总价值为: " << maxTotalValue << endl;
    return 0;
}