Skip to content

Commit 0bc3b6b

Browse files
authored
Create Fractional_knapsack.cpp
1 parent 2238be6 commit 0bc3b6b

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

DP/Knapsack/Fractional_knapsack.cpp

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
2+
// C/C++ program to solve fractional Knapsack Problem
3+
#include <bits/stdc++.h>
4+
5+
using namespace std;
6+
7+
// Structure for an item which stores weight and corresponding
8+
// value of Item
9+
struct Item
10+
{
11+
int value, weight;
12+
13+
// Constructor
14+
Item(int value, int weight) : value(value), weight(weight)
15+
{}
16+
};
17+
18+
// Comparison function to sort Item according to val/weight ratio
19+
bool cmp(struct Item a, struct Item b)
20+
{
21+
double r1 = (double)a.value / a.weight;
22+
double r2 = (double)b.value / b.weight;
23+
return r1 > r2;
24+
}
25+
26+
// Main greedy function to solve problem
27+
double fractionalKnapsack(int W, struct Item arr[], int n)
28+
{
29+
// sorting Item on basis of ratio
30+
sort(arr, arr + n, cmp);
31+
32+
// Uncomment to see new order of Items with their ratio
33+
/*
34+
for (int i = 0; i < n; i++)
35+
{
36+
cout << arr[i].value << " " << arr[i].weight << " : "
37+
<< ((double)arr[i].value / arr[i].weight) << endl;
38+
}
39+
*/
40+
41+
int curWeight = 0; // Current weight in knapsack
42+
double finalvalue = 0.0; // Result (value in Knapsack)
43+
44+
// Looping through all Items
45+
for (int i = 0; i < n; i++)
46+
{
47+
// If adding Item won't overflow, add it completely
48+
if (curWeight + arr[i].weight <= W)
49+
{
50+
curWeight += arr[i].weight;
51+
finalvalue += arr[i].value;
52+
}
53+
54+
// If we can't add current Item, add fractional part of it
55+
else
56+
{
57+
int remain = W - curWeight;
58+
finalvalue += arr[i].value * ((double) remain / arr[i].weight);
59+
break;
60+
}
61+
}
62+
63+
// Returning final value
64+
return finalvalue;
65+
}
66+
67+
// driver program to test above function
68+
int main()
69+
{
70+
int W = 50; // Weight of knapsack
71+
Item arr[] = {{60, 10}, {100, 20}, {120, 30}};
72+
73+
int n = sizeof(arr) / sizeof(arr[0]);
74+
75+
cout << "Maximum value we can obtain = "
76+
<< fractionalKnapsack(W, arr, n);
77+
return 0;
78+
}

0 commit comments

Comments
 (0)