使用贪心算法解决背包问题,物品的(体积:价值)分别为{2, 3}, {3, 6}, {4, 9}, {2, 7}。背包的容量为5,要求:将4个物品装入背包使其得到的价值最大。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Item {
int weight;
int value;
};
bool compare(Item item1, Item item2) {
double ratio1 = (double)item1.value / item1.weight;
double ratio2 = (double)item2.value / item2.weight;
return ratio1 > ratio2;
}
int knapsack(int capacity, vector<Item>& items) {
sort(items.begin(), items.end(), compare);
int totalValue = 0;
int currentWeight = 0;
for (int i = 0; i < items.size(); i++) {
if (currentWeight + items[i].weight <= capacity) {
currentWeight += items[i].weight;
totalValue += items[i].value;
}
}
return totalValue;
}
int main() {
Item item1;
item1.weight = 2;
item1.value = 3;
Item item2;
item2.weight = 3;
item2.value = 6;
Item item3;
item3.weight = 4;
item3.value = 9;
Item item4;
item4.weight = 2;
item4.value = 7;
vector<Item> items;
items.push_back(item1);
items.push_back(item2);
items.push_back(item3);
items.push_back(item4);
int capacity = 5;
int maxValue = knapsack(capacity, items);
cout << "Max value: " << maxValue << endl;
return 0;
}