-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfractional final.cpp
More file actions
72 lines (59 loc) · 1.41 KB
/
fractional final.cpp
File metadata and controls
72 lines (59 loc) · 1.41 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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
double FracKnap(vector<int> p, vector<int> w, int c, int n)
{
vector<pair<double, pair<int,int>>> items;
for (int i = 0; i < n; i++)
{
double ratio = (double)p[i]/w[i];
items.push_back({ratio, {p[i], w[i]}});
}
sort(items.rbegin(), items.rend());
double totalP = 0.0;
int rem_cap = c;
for (int i = 0; i < n; i++)
{
int current_p = items[i].second.first;
int current_w = items[i].second.second;
if (current_w <= rem_cap)
{
totalP += current_p;
rem_cap -= current_w;
}
else
{
totalP += rem_cap * items[i].first;
break;
}
}
return totalP;
}
int main()
{
vector<int> p;
vector<int> w;
int c, n;
cout << "Enter the number of items :" << endl;
cin >> n;
cout << "Enter the price of items :" << endl;
for (int i = 0; i < n; i++)
{
int price;
cin >> price;
p.push_back(price);
}
cout << "Enter the weight of items :" << endl;
for (int i = 0; i < n; i++)
{
int weight;
cin >> weight;
w.push_back(weight);
}
cout << "Enter the capacity of the knapsack : " << endl;
cin >> c;
double maxP = FracKnap(p, w, c, n);
cout << "Maximum Profit: " << maxP << endl;
return 0;
}