Fractional knapsack problem (greedy algorithm)

Source: Internet
Author: User

#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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.