#include<iostream> #include<iterator> #include<vector> #include<algorithm> using namespace std; /* *分数背包问题(贪心算法) */ struct goods { double value;//物品的价值 double weight;//物品的重量 double ratio;//物品的性价比 double in;//物品装入背包的重量 int index;//物品的编号 friend ostream & operator<<(ostream & o,const goods & g); friend istream & operator>>(istream & o,goods & g); }; ostream & operator<<(ostream & o,const goods & g) { o<<"物品编号: "<<g.index<<" 物品装入背包的重量 "<<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) { //先将货物按照性价比排序 sort(vec.begin(),vec.end(),cmp); //从性价比高的开始装入背包 double l = v;//背包的剩余容量 double sum = 0;//背包的总价值 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;//可选物品向量 //输入可选物品 copy(istream_iterator<goods>(cin),istream_iterator<goods>(),back_inserter(vec_goods)); double wei_bag;//背包的承载最大重量 cin.clear(); cin.sync(); cin>>wei_bag; double max_v = knapsack(vec_goods,wei_bag); cout<<"背包可以装载的最大价值为: "<<max_v<<endl; cout<<"分别承载的物品和重量为"<<endl; copy(vec_goods.begin(),vec_goods.end(),ostream_iterator<goods>(cout," ")); cout<<endl; }
时间: 2024-10-10 10:15:33