-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathknapsackusinggreedy.cpp
More file actions
41 lines (34 loc) · 979 Bytes
/
Copy pathknapsackusinggreedy.cpp
File metadata and controls
41 lines (34 loc) · 979 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Item {
int value, weight;
};
bool compare(Item a, Item b) {
double r1 = (double)a.value / a.weight;
double r2 = (double)b.value / b.weight;
return r1 > r2;
}
double fractionalKnapsack(int W, vector<Item>& items) {
sort(items.begin(), items.end(), compare);
double totalValue = 0.0;
int currentWeight = 0;
for (auto& item : items) {
if (currentWeight + item.weight <= W) {
currentWeight += item.weight;
totalValue += item.value;
} else {
int remainingWeight = W - currentWeight;
totalValue += (double)item.value * ((double)remainingWeight / item.weight);
break;
}
}
return totalValue;
}
int main() {
int W = 50;
vector<Item> items = {{60, 10}, {100, 20}, {120, 30}};
cout << "Maximum value: " << fractionalKnapsack(W, items) << endl;
return 0;
}