贪心法背包问题c++
时间: 2023-12-20 14:32:00 浏览: 79
以下是使用贪心算法解决背包问题的C++代码示例:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Item {
int weight;
int value;
double ratio;
};
bool compare(Item a, Item b) {
return a.ratio > b.ratio;
}
double knapsack(int capacity, vector<Item>& items) {
sort(items.begin(), items.end(), compare);
double totalValue = 0.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;
} else {
int remainingCapacity = capacity - currentWeight;
totalValue += items[i].ratio * remainingCapacity;
break;
}
}
return totalValue;
}
int main() {
int capacity = 10;
vector<Item> items = {{2, 10}, {3, 5}, {5, 15}, {7, 7}, {1, 6}, {4, 18}, {1, 3}};
double maxValue = knapsack(capacity, items);
cout << "Maximum value that can be carried: " << maxValue << endl;
return 0;
}
```
阅读全文