编辑代码

#include <iostream>
#include <algorithm>

using namespace std;

// 定义水果的结构体
struct Fruit {
    string name;
    int weight;
    int value;
};

// 贪心算法,按单位重量的价值降序排序
bool compare(const Fruit& a, const Fruit& b) {
    return (a.value / a.weight) > (b.value / b.weight);
}

// 装背包的函数
void fillBackpack(Fruit fruits[], int n, int capacity) {
    sort(fruits, fruits + n, compare);  // 按单位重量的价值降序排序

    int currentWeight = 0;
    int totalValue = 0;

    cout << "装入水果的策略:" << endl;

    for (int i = 0; i < n; ++i) {
        if (currentWeight + fruits[i].weight <= capacity) {
            // 可以装入整个水果
            currentWeight += fruits[i].weight;
            totalValue += fruits[i].value;
            cout << "装入 " << fruits[i].name << ",重量:" << fruits[i].weight << "kg,价值:" << fruits[i].value << "元" << endl;
        } else {
            // 只能装入一部分水果
            int remainingWeight = capacity - currentWeight;
            double partialValue = (static_cast<double>(remainingWeight) / fruits[i].weight) * fruits[i].value;
            currentWeight = capacity;
            totalValue += partialValue;
            cout << "装入 " << fruits[i].name << " 的一部分,重量:" << remainingWeight << "kg,价值:" << partialValue << "元" << endl;
            break;  // 背包已经装满
        }
    }

    cout << "总重量:" << currentWeight << "kg,总价值:" << totalValue << "元" << endl;
}

int main() {
    Fruit fruits[] = {
        {"苹果", 15, 300},
        {"香蕉", 18, 180},
        {"橘子", 10, 150},
        {"猕猴桃", 9, 270}
    };

    int n = sizeof(fruits) / sizeof(fruits[0]);  // 计算水果的数量
    int backpackCapacity = 20;

    fillBackpack(fruits, n, backpackCapacity);

    return 0;
}