-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfractional_knapsack.cpp
More file actions
47 lines (43 loc) · 1015 Bytes
/
fractional_knapsack.cpp
File metadata and controls
47 lines (43 loc) · 1015 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
42
43
44
45
46
47
// Online C++ compiler to run C++ program online
#include <bits/stdc++.h>
using namespace std;
struct Item
{
int weight;
int value;
};
// custom comparator based on value by 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 fractional_knapsack(vector<Item> &items, int capacity)
{
sort(items.begin(), items.end(), compare);
int current_cap = capacity;
double profit = 0;
for (auto item : items)
{
if (item.weight <= current_cap)
{
profit += item.value;
current_cap -= item.weight;
}
else
{
profit += item.value * ((double)current_cap / item.weight);
break;
}
}
return profit;
}
int main()
{
vector<Item> items = {{10, 60}, {20, 100}, {30, 120}};
int capacity = 50;
double max_profit = fractional_knapsack(items, capacity);
cout << max_profit;
return 0;
}