-
Notifications
You must be signed in to change notification settings - Fork 0
/
FractionalKnapsack.cpp
81 lines (59 loc) · 1.29 KB
/
FractionalKnapsack.cpp
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
#include<bits/stdc++.h>
using namespace std;
struct Item
{
string name;
float price, weight, per_unit;
};
bool sortCmp(Item a1, Item a2)
{
return(a1.per_unit>a2.per_unit);
}
int knapSack(Item arr[], int w, int n)
{
sort(arr,arr+n, sortCmp);
float total=0;
for(int i =0; i<n; i++)
{
if(w>=arr[i].weight)
{
total += arr[i].price;
w-=arr[i].weight;
cout << arr[i].name << " " << arr[i].price << endl;
}
else
{
cout << arr[i].name << " " <<arr[i].per_unit * w<< endl;
total += arr[i].per_unit * w;
break;
}
}
cout << "Total Profit: " << total << endl;
}
int main()
{
int n;
cout << "Enter The Item Number: ";
cin >> n;
Item arr[n];
for(int i = 0; i<n; i++)
{
/* Price & Weight Input */
cin >> arr[i].name >> arr[i].price >> arr[i].weight;
/* Per Unit Price Stored */
arr[i].per_unit = arr[i].price / arr[i].weight;
}
/* Knap Sack Capacity Input */
int w;
cout << "KnapSack Capacity: ";
cin >> w;
knapSack( arr, w, n);
return 0;
}
/*
Input Value
3
A 60 10
B 100 20
C 120 30
*/