-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfractional_knapsack.cpp
More file actions
61 lines (49 loc) · 1.23 KB
/
fractional_knapsack.cpp
File metadata and controls
61 lines (49 loc) · 1.23 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
#include <iostream>
#include "fractional_knapsack.h"
int main()
{
double ratio = 0.0, total = 0.0, profit = 0.0;
int item = 0, kcap = 0, k = 0;
std::cout << "Enter the capacity of the knapsack" << std::endl;
std::cin >> kcap;
std::cout << "Enter the no of items" << std::endl;
std::cin >> item;
Choice kp[item], temp;
std::cout << "Enter the weight and value of items" << std::endl;
for(int i = 0; i < item; i++)
{
std::cin >> kp[i].weight;
std::cin >> kp[i].value;
}
for(int i = 0; i < item; i++)
{
kp[i].ratio = kp[i].value / kp[i].weight;
}
std::cout << "Arranging the ratio in descending order" << std::endl;
for(int i = 0; i < item; i++)
{
for(int j = 0; j < item - i - 1; j++)
{
if(kp[j + 1].ratio > kp[j].ratio)
{
temp = kp[j];
kp[j] = kp[j + 1];
kp[j + 1] = temp;
}
}
}
std::cout << "The ratio in descending order is" << std::endl;
for(int i = 0; i < item; i++)
{
kp[i].flag = false;
std::cout << kp[i].ratio << std::endl;
}
for(k = 0; total + kp[k].weight < kcap; k++)
{
total += kp[k].weight;
kp[k].flag = true;
profit += kp[k].value;
}
profit += kp[k].value * (kcap - total) / kp[k].weight ;
std::cout << "The profit is" << profit << std::endl;
}