This repository was archived by the owner on May 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFractionalKnapsack.cpp
More file actions
53 lines (52 loc) · 1.59 KB
/
FractionalKnapsack.cpp
File metadata and controls
53 lines (52 loc) · 1.59 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
#include<iostream>
using namespace std;
int main()
{
int array[2][100], n, w, i, curw, used[100], maxi = -1, totalprofit = 0;
cout << "Enter number of objects: ";
cin >> n;
cout << "Enter the weight of the knapsack: ";
cin >> w;
for (i = 0; i < n; i++)
{
cout << "\nEnter weight of object " << i+1 << ": ";
cin >> array[0][i];
cout << "Enter profit of object " << i+1 << ": ";
cin>> array[1][i];
}
for (i = 0; i < n; i++)
{
used[i] = 0;
}
curw = w;
cout << endl;
cout << endl;
cout<<"Object\t\t" <<"Weight\t\t"<<"Profit\t\t"<<"FreeSpace\t\t"<<endl;
while (curw >= 0)
{
maxi = -1;
for (i = 0; i < n; i++)
{
if ((used[i] == 0) && ((maxi == -1) || (((float) array[1][i]/(float) array[0][i]) > ((float) array[1][maxi]/ (float) array[0][maxi]))))
{
maxi = i;
}
}
used[maxi] = 1;
curw -= array[0][maxi];
totalprofit += array[1][maxi];
if (curw >= 0)
{
cout << maxi + 1 << "\t\t"<< array[0][maxi] <<"\t\t" << array[1][maxi]<< "\t\t" << curw;
}
else
{
cout << maxi + 1 << "\t\t"<< (array[0][maxi] + curw) << "\t\t"<< (array[1][maxi] / array[0][maxi]) * (array[0][maxi]+ curw) << "\t\t" << curw + array[0][maxi];
totalprofit -= array[1][maxi];
totalprofit += ((array[1][maxi] / array[0][maxi]) * (array[0][maxi]+ curw));
}
cout<<endl;
}
cout << "\nMaximum Profit: " << totalprofit << endl;
return 0;
}