-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFractionalKnapsack.cpp
More file actions
97 lines (79 loc) · 1.62 KB
/
FractionalKnapsack.cpp
File metadata and controls
97 lines (79 loc) · 1.62 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <bits/stdc++.h>
using namespace std;
struct item
{
double price;
double weight;
double ppw;
item(double p, double w)
{
price = p;
weight = w;
ppw = p / w;
}
};
class FracKnapsack
{
private:
int _size;
double maxWeight;
vector<item> objArray;
public:
void takeInput();
double calMaxProfit();
void printArray();
};
void FracKnapsack::takeInput()
{
cout << "Number of objects:";
cin >> _size;
cout << "Input price and weight:" << endl;
for (int i = 0; i < _size; i++) // taking all the inputs
{
int p, w;
cin >> p >> w;
objArray.emplace_back(item(p, w));
}
cout << "Max Weight:";
cin >> maxWeight;
}
bool compPpw(item a, item b)
{
if (a.ppw == b.ppw) // if ppw is matched, we want one with greater weight between them
return a.weight > b.weight;
return a.ppw > b.ppw;
}
double FracKnapsack::calMaxProfit()
{
sort(objArray.begin(), objArray.end(), compPpw); // sorting the array according to ppw of all items
double remWeight = maxWeight, maxProfit = 0;
for (auto v : objArray)
{
if (v.weight <= remWeight) // full weight is takeable as remaining weight is greater
{
remWeight -= v.weight;
maxProfit += v.price;
}
else
{
maxProfit += remWeight * v.ppw; // we are taking fraction of the item, because remaining weight is not enough
break;
}
}
return maxProfit;
}
void FracKnapsack::printArray()
{
for (auto v : objArray)
{
cout << v.price << "->" << v.weight << "->" << v.ppw << "->taken frac:" << v.frac << endl;
}
}
int main()
{
FracKnapsack *demo1 = new FracKnapsack();
demo1->takeInput();
cout << demo1->calMaxProfit() << endl;
demo1->printArray();
return 0;
}