-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathFractional_knapsack
47 lines (39 loc) · 1.11 KB
/
Fractional_knapsack
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
#include <bits/stdc++.h>
using namespace std;
struct Item {
int value;
int weight;
};
class Solution {
public:
bool static comp(Item a, Item b) {
double r1 = (double) a.value / (double) a.weight;
double r2 = (double) b.value / (double) b.weight;
return r1 > r2;
}
// function to return fractionalweights
double fractionalKnapsack(int W, Item arr[], int n) {
sort(arr, arr + n, comp);
int curWeight = 0;
double finalvalue = 0.0;
for (int i = 0; i < n; i++) {
if (curWeight + arr[i].weight <= W) {
curWeight += arr[i].weight;
finalvalue += arr[i].value;
} else {
int remain = W - curWeight;
finalvalue += (arr[i].value / (double) arr[i].weight) * (double) remain;
break;
}
}
return finalvalue;
}
};
int main() {
int n = 3, weight = 50;
Item arr[n] = { {100,20},{60,10},{120,30} };
Solution obj;
double ans = obj.fractionalKnapsack(weight, arr, n);
cout << "The maximum value is " << setprecision(2) << fixed << ans;
return 0;
}