We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent c4f13ea commit 26fa7c6Copy full SHA for 26fa7c6
frac_knapsack.cpp
@@ -0,0 +1,33 @@
1
+#include <bits/stdc++.h>
2
+#define ll long long
3
+#define pll pair<ll,ll>
4
+using namespace std;
5
+
6
+bool comp(pll a, pll b) {
7
+ float ratio1 = float(a.first)/float(a.second);
8
+ float ratio2 = float(b.first)/float(b.second);
9
+ return ratio1 > ratio2;
10
+}
11
12
+int main() {
13
+ ll i,value,weight,n,w;
14
+ cin>>n>>w;
15
+ vector<pll > ratio;
16
+ for(i=0;i<n;i++) {
17
+ cin>>value>>weight;
18
+ ratio.push_back(make_pair(value,weight));
19
+ }
20
+ sort(ratio.begin(), ratio.end(), comp);
21
+ float res = 0.0;
22
+ i = 0;
23
+ while(i<n && w-ratio[i].second >= 0) {
24
+ res += ratio[i].first;
25
+ w -= ratio[i].second;
26
+ i++;
27
28
+ if(i<n) {
29
+ res += (float(ratio[i].first)/float(ratio[i].second))*w;
30
31
+ cout<<res<<endl;
32
+ return 0;
33
0 commit comments