编辑代码

#include <iostream>
#include <algorithm>

using namespace std;

struct Bean {
    int weight;
    int value;
};

bool compare(Bean a, Bean b) {
    return (double)a.value / a.weight > (double)b.value / b.weight;
}

int maxBeanValue(Bean beans[], int numBeans, int capacity) {
    sort(beans, beans + numBeans, compare);

    int totalValue = 0;
    int currentWeight = 0;

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

    return totalValue;
}

int main() {
    // 示例用法
    const int numBeans = 5;
    Bean beans[numBeans] = {{2, 10}, {3, 5}, {5, 15}, {7, 7}, {1, 6}};
    int capacity = 15;

    int result = maxBeanValue(beans, numBeans, capacity);

    cout << "Maximum value in the knapsack: " << result << endl;

    return 0;
}