forked from SRIJONDEY/MU_DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFractional_Knapsack.cpp
More file actions
75 lines (60 loc) · 1.32 KB
/
Copy pathFractional_Knapsack.cpp
File metadata and controls
75 lines (60 loc) · 1.32 KB
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
//
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
double FracKnap(vector<int> p1, vector<int> w2, int capacity, int n)
{
vector<pair<double, pair<int, int>>> items;
for (int i = 0; i < n; i++)
{
double ratio = (double)p1[i] / w2[i];
items.push_back({ratio, {p1[i], w2[i]}});
}
sort(items.rbegin(), items.rend());
double totalp = 0.0;
int rem_capacity = capacity;
for (int i = 0; i < n; i++)
{
int p = items[i].second.first;
int w = items[i].second.second;
if (w <= rem_capacity)
{
totalp += p;
rem_capacity -= w;
}
else
{
totalp += rem_capacity * items[i].first;
break; // knapsack full
}
}
return totalp;
}
int main()
{
int n;
cout << "Enter number of items: ";
cin >> n;
int capacity;
cout << "Enter knapsack capacity: ";
cin >> capacity;
vector<int> p1, w2;
cout << "Enter profits: ";
for (int i = 0; i < n; i++)
{
int price;
cin >> price;
p1.push_back(price);
}
cout << "Enter weights: ";
for (int i = 0; i < n; i++)
{
int weight;
cin >> weight;
w2.push_back(weight);
}
double maxProfit = FracKnap(p1, w2, capacity, n);
cout << "Maximum Profit = " << maxProfit << endl;
return 0;
}