-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathFractional Knapsack.txt
87 lines (80 loc) · 1.8 KB
/
Fractional Knapsack.txt
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
#include <iostream>
#include<conio.h>
#include<stdio.h>
using namespace std;
typedef struct{
int v;
int w;
float d;
}Item;
void input(Item items[],int sizeOfItems)
{
cout << "Enter total "<< sizeOfItems <<" item's values and weight" << endl;
for(int i = 0; i < sizeOfItems; i++)
{
cout << "Enter "<< i+1 << " Value: ";
cin >> items[i].v;
cout << "Enter "<< i+1 << " value Weight: ";
cin >> items[i].w;
}
}
void display(Item items[], int sizeOfItems)
{
int i;
cout << "values: ";
for(i = 0; i < sizeOfItems; i++)
{
cout << items[i].v << "\t";
}
cout << endl << "weight: ";
for (i = 0; i < sizeOfItems; i++)
{
cout << items[i].w << "\t";
}
cout << endl;
}
bool compare(Item i1, Item i2)
{
return (i1.d > i2.d);
}
float knapsack(Item items[], int sizeOfItems, int W)
{
int i, j, pos;
Item mx, temp;
float totalValue = 0, totalWeight = 0;
for (i = 0; i < sizeOfItems; i++) {
items[i].d = items[i].v / items[i].w;
}
for(i=0; i<sizeOfItems; i++)
{
if(totalWeight + items[i].w<= W)
{
totalValue += items[i].v ;
totalWeight += items[i].w;
}
else
{
int wt = W-totalWeight;
totalValue += (wt * items[i].d);
totalWeight += wt;
break;
}
}
cout << "total weight in bag:" << totalWeight<<endl;
return totalValue;
}
int main()
{
int W,n;
Item items[25];
cout << "Enter the number of elements: ";
cin >> n;
input(items, n);
cout << "Entered data: \n";
display(items,n);
cout<< "Enter Knapsack weight: \n";
cin >> W;
float mxVal = knapsack(items, n, W);
cout << "Max value for "<< W <<" weight is: "<< mxVal;
getch();
}