forked from Raiyan-sharif/Algorithm-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGreedyExample.cpp
More file actions
43 lines (39 loc) · 1005 Bytes
/
GreedyExample.cpp
File metadata and controls
43 lines (39 loc) · 1005 Bytes
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
#include<iostream>
#include<algorithm>
using namespace std;
struct knapsack {
int unitPrice, quantity;
};
bool cmp( knapsack A, knapsack B ) {
return A.unitPrice < B.unitPrice;
}
int main() {
int i, n, k, res;
knapsack knap[100];
cin >> n >> k;
for( i = 0; i < n; i++ ) {
cin >> knap[i].unitPrice >> knap[i].quantity;
}
sort( knap, knap + n, cmp );
cout << endl << "Sorted List:" << endl;
for( int i = 0; i < n; i++ ) {
cout << knap[i].unitPrice << " " << knap[i].quantity << endl;
}
cout << endl;
i = 0;
res = 0;
for( i = 0, res= 0; k > 0 && i < n; i++ ) {
int taking;
if( knap[i].quantity <= k ) {
k -= knap[i].quantity;
taking = knap[i].quantity;
}
else {
taking = k;
k = 0;
}
res += ( taking * knap[i].unitPrice );
}
cout << "Minimum Cost: " << res << endl;
return 0;
}