-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfractionalKnapsack.cpp
More file actions
76 lines (67 loc) · 1.47 KB
/
fractionalKnapsack.cpp
File metadata and controls
76 lines (67 loc) · 1.47 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
#include <bits/stdc++.h>
using namespace std;
void knapsack(int n, float wt[], float pf[], float capacity)
{
float rem_wt = capacity;
int i = 0;
float total_pf = 0;
while (rem_wt > 0)
{
if (wt[i] <= rem_wt)
{
total_pf = total_pf + pf[i];
rem_wt = rem_wt - wt[i];
i++;
}
else
{
total_pf = total_pf + pf[i] / wt[i] * rem_wt;
rem_wt = 0;
}
}
cout << "maximum profit :" << total_pf;
}
int main()
{
int n;
cout << "enter number of items :";
cin >> n;
float wt[n];
float pf[n];
int i, j, temp;
for (i = 0; i < n; i++)
{
cout << "enter weight of item:";
cin >> wt[i];
cout << "enter value of item:";
cin >> pf[i];
}
float capacity;
cout << "enter capacity of knapsack :";
cin >> capacity;
float retio[n];
for (i = 0; i < n; i++)
{
retio[i] = pf[i] / wt[i];
}
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (retio[i] < retio[j])
{
temp = retio[j];
retio[j] = retio[i];
retio[i] = temp;
temp = wt[j];
wt[j] = wt[i];
wt[i] = temp;
temp = pf[j];
pf[j] = pf[i];
pf[i] = temp;
}
}
}
knapsack(n, wt, pf, capacity);
return 0;
}