#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;
}