编辑代码

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

// 定义一个结构体,表示每种豆子的名称,重量,价值和单价
struct Bean {
    string name;
    double weight;
    double value;
    double price;
};

// 定义一个比较函数,按照单价从高到低排序
bool compare(Bean a, Bean b) {
    return a.price > b.price;
}

// 定义一个贪心函数,返回背包中的最大价值
double greedyKnapsack(double capacity, Bean beans[], int n) {
    // 对豆子按照单价从高到低排序
    sort(beans, beans + n, compare);
    // 初始化当前重量和当前价值为0
    double currentWeight = 0;
    double currentValue = 0;
    // 遍历每种豆子
    for (int i = 0; i < n; i++) {
        // 如果当前豆子可以全部放入
        if (currentWeight + beans[i].weight <= capacity) {
            // 更新当前重量和当前价值
            currentWeight += beans[i].weight;
            currentValue += beans[i].value;
            // 输出放入的豆子的信息
            cout << "Put all " << beans[i].name << " into the knapsack, weight: " << beans[i].weight << ", value: " << beans[i].value << endl;
        }
        // 如果当前豆子只能放入部分
        else {
            // 计算剩余的空间
            double remain = capacity - currentWeight;
            // 更新当前重量和当前价值
            currentWeight += remain;
            currentValue += remain * beans[i].price;
            // 输出放入的豆子的信息
            cout << "Put part of " << beans[i].name << " into the knapsack, weight: " << remain << ", value: " << remain * beans[i].price << endl;
            // 结束循环
            break;
        }
    }
    // 返回最大价值
    return currentValue;
}

int main() {
    // 定义背包的容量
    double capacity = 100;
    // 定义豆子的数量
    int n = 5;
    // 定义每种豆子的信息
    Bean beans[] = {
        {"黄豆", 50, 60, 1.2},
        {"绿豆", 40, 40, 1},
        {"红豆", 30, 30, 1},
        {"黑豆", 20, 80, 4},
        {"青豆", 10, 100, 10}
    };
    // 调用贪心函数,得到最大价值
    double maxValue = greedyKnapsack(capacity, beans, n);
    // 输出最大价值
    cout << "The maximum value is: " << maxValue << endl;
    return 0;
}