#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);
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 << "放入全部 " << beans[i].name << " 到背包里, 重量是: " << beans[i].weight << ", 价值是: " << beans[i].value << endl;
}
else {
double remain = capacity - currentWeight;
currentWeight += remain;
currentValue += remain * beans[i].price;
cout << "放入部分 " << beans[i].name << " 到背包里, 重量是: " << remain << ", 价值是: " << 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 << "最大价值是: " << maxValue << endl;
return 0;
}