Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 26fa7c6

Browse files
Fractional knapsack
1 parent c4f13ea commit 26fa7c6

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

‎frac_knapsack.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /