Created
August 3, 2018 11:03
-
-
Save gallirohik/44e18bea88d317ed8ef87eabe35d11bb to your computer and use it in GitHub Desktop.
fractional knapsack problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <cmath> | |
| #include <cstdio> | |
| #include <vector> | |
| #include <iostream> | |
| #include <algorithm> | |
| #include<utility> | |
| #include<iomanip> | |
| using namespace std; | |
| bool myfunction( pair<int,int> a,pair<int,int> b) | |
| { | |
| return ((double)a.second/a.first) >((double)b.second/b.first) ; | |
| } | |
| void mygold(vector< pair<int,int> > &samples,int N,int W) | |
| { | |
| sort(samples.begin(),samples.end(),myfunction); | |
| double myMoney=0;int i; | |
| for(i=0 ; (i<N) && ( W );i++) | |
| { | |
| if(W>=samples[i].first) | |
| { | |
| myMoney+=(double)samples[i].second; | |
| W-=samples[i].first; | |
| } | |
| else | |
| { | |
| myMoney+=(W)*((double)samples[i].second/(double)samples[i].first); | |
| W=0; | |
| } | |
| } | |
| if((i==N)&&(W!=0)) | |
| cout<<-1; | |
| else {std::cout << std::fixed; | |
| cout<<std::setprecision(12)<<myMoney; | |
| } | |
| } | |
| int main() { | |
| /* Enter your code here. Read input from STDIN. Print output to STDOUT */ | |
| int N,W,w,v; | |
| cin>>N>>W; | |
| pair<int,int>s; | |
| vector< pair<int,int> > samples; | |
| int sum=0; | |
| for(int i=0;i<N;i++) | |
| { | |
| cin>>w>>v; | |
| sum+=w; | |
| s=make_pair(w,v); | |
| samples.push_back(s); | |
| } | |
| mygold(samples,N,W); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment