-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfractionalKnapsack.cpp
More file actions
72 lines (55 loc) · 1.26 KB
/
fractionalKnapsack.cpp
File metadata and controls
72 lines (55 loc) · 1.26 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
#include<bits/stdc++.h>
using namespace std;
class Item
{
public:
double val,wt;
};
bool compare(Item a,Item b)
{
double rat1=a.val/a.wt;
double rat2=b.val/b.wt;
return (rat1>rat2);
}
double knapsack(Item item[],int N,int W)
{
double currentWt=0,finalVal=0;
sort(item,item+N,compare);
for(int i=0;i<N;i++)
{
if((currentWt+item[i].wt)<=W)
{
currentWt+=item[i].wt;
finalVal+=item[i].val;
}
else
{
double remaining=W-currentWt;
double unitWt=item[i].val/item[i].wt;
finalVal+=(remaining*unitWt);
break;
}
}
return finalVal;
}
int main()
{
Item item[1000];
int N,i;
double W;
printf("Enter the number of items:");
scanf("%d",&N);
printf("\n");
for(i=0;i<N;i++)
{
printf("Item %d:\n",i+1);
printf("Enter value:");
scanf("%lf",&item[i].val);
printf("Enter weight:");
scanf("%lf",&item[i].wt);
}
printf("Enter Knapsack capacity : ");
scanf("%lf",&W);
printf("The maximum value that can be put into the knapsack is :%.2lf\n",knapsack(item,N,W));
return 0;
}