-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFractionalKnapsack.cpp
75 lines (65 loc) · 1.55 KB
/
FractionalKnapsack.cpp
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
struct Item {
int value;
int weight;
};
// } Driver Code Ends
//class implemented
/*
struct Item{
int value;
int weight;
};
*/
class Solution
{
public:
//Function to get the maximum total value in the knapsack.
double fractionalKnapsack(int W, Item arr[], int n)
{
multimap<double, pair<int, int>> mp;
double wt, val;
for (int i = 0; i < n; i++) {
wt = arr[i].weight;
val = arr[i].value;
double weVal = wt / val;
mp.insert({weVal, {val, wt}});
}
double ans = 0, curWt = 0;
for (auto ele : mp) {
if (curWt + ele.second.second <= W) {
ans += ele.second.first;
curWt += ele.second.second;
} else {
int remain = W - curWt;
ans += ele.second.first * ((double)remain / (double)ele.second.second);
break;
}
}
return ans;
}
};
// { Driver Code Starts.
int main()
{
int t;
//taking testcases
cin >> t;
cout << setprecision(2) << fixed;
while (t--) {
//size of array and weight
int n, W;
cin >> n >> W;
Item arr[n];
//value and weight of each item
for (int i = 0; i < n; i++) {
cin >> arr[i].value >> arr[i].weight;
}
//function call
Solution ob;
cout << ob.fractionalKnapsack(W, arr, n) << endl;
}
return 0;
} // } Driver Code Ends