#include <iostream> #include <iterator> #include <vector> #include <algorithm>using namespace std;/** fractional knapsack problem (greedy algorithm) */struct goods{double value;//Item value double weight;//Item weight double ratio;//item Cost-effective double in;// Item load Backpack weight int index;//item's number friend Ostream & operator<< (Ostream & O,const goods & G); Friend IStream & Operator>> (IStream & O,goods & G);};o Stream & operator<< (Ostream & O,const Goods & G) {o<< "Item Number:" <<g.index<< "weight of items loaded into backpack" <<g.in<<endl;return o;} IStream & Operator>> (IStream & O,goods & G) {o>>g.index>>g.weight>>g.value; G.ratio = G.value/g.weight;return o;} BOOL CMP (Goods g1,goods G2) {if (G1.ratio>g2.ratio) {return true;} Else{return false;}} Double knapsack (vector<goods> & Vec,double v) {//order goods to be sorted by price/performance (Vec.begin (), Vec.end (), CMP) first;// Load the backpack from a cost-effective start double L = v;//Backpack's remaining capacity double sum = 0;//Backpack's total value for (int i = 0; i < vec.size (); i++) {if (l>0) {if(L>vec[i].weight) {L-= vec[i].weight;vec[i].in = Vec[i].weight;sum + = Vec[i].value;} else{vec[i].in = vec[i].weight-l;sum + = L*vec[i].ratio;l =0;break;}}} return sum;} int main () {vector<goods> vec_goods;//Optional Item vector//input optional Item copy (Istream_iterator<goods> (CIN), ISTREAM_ Iterator<goods> (), Back_inserter (vec_goods));d ouble wei_bag;//backpack carrying the maximum weight cin.clear (); Cin.sync ();cin>> Wei_bag;double Max_v = knapsack (vec_goods,wei_bag);cout<< "Backpack can load the maximum value for:" <<max_v<<endl;cout< < "<<endl;copy (Vec_goods.begin (), Vec_goods.end (),ostream_iterator<goods> (cout," ") of the items and weights respectively; Cout<<endl;}
Fractional knapsack problem (greedy algorithm)