#include"iostream"
#include "vector"
#include<algorithm>
#include <functional>
using namespace std;
class Greedy
{
public :
Greedy(int x,vector<int >a,vector<float>b) ;
void Uint();
void profit();
private:
int weight;
vector<int> storeweight;
vector<float>everybagprofit;
vector<float>unitprofit;
};
Greedy::Greedy(int x,vector<int >a,vector<float>b)//存放物品重量和价格
{
weight=x;
a.swap (storeweight);
b.swap (everybagprofit);
}
void Greedy::Uint()//求解单位重量的价格
{
float value ;
for(int i= 0;i<storeweight.size();i++)
{
value= everybagprofit[i]/storeweight[i];
unitprofit.push_back(value);
}
}
void Greedy::profit()//求解利润
{
float benefit,total=0;
int ref=0;
int i=0,j=0 ;
benefit=*max_element(unitprofit.begin(),unitprofit.end()); //求出单位价值Vcetor中的
//最大值
do
{
for( j ;j<unitprofit.size ()&&weight!=0;)
{
if(unitprofit[j]==benefit)
{
ref=j;
j=i++;
break;
}
else
{
j=i++;
continue;
}
}//此循环用于找出对应最大利润的物品位置便于找到其重量
if(storeweight[ref]<weight)//判断重量是否大于背包的重量
{
total=unitprofit[ref]*storeweight[ref];
weight=weight-storeweight[ref];
}
else
{
if(weight<=0)
break;
else
{
total+=unitprofit[ref] * weight;
weight=weight-storeweight[ref];
}
}
remove(unitprofit.begin(),unitprofit.end(),benefit);//移除计算过的最大利润数值
i=0;j=0;
}while(weight!=0);
cout<<"最大收益为"<<total;
}
int main()
{
int Weight,weight,bagsNumber;
float benefit;
vector<int>bagsweight ;
vector<float>bagsprofit ;
cout<<"请输入背包的总重量"<<endl;
cin>>Weight;
cout<<endl;
// Greedy greedy1(Weight);
cout<<"请输入物品的个数"<<endl;
cin>>bagsNumber;
cout<<endl;
cout<<"请输入每个物品的重量"<<endl;
for(int i=0;i<bagsNumber;i++)
{
cin>>weight;
bagsweight.push_back(weight);
}
cout<<endl;
cout<<"请输入物品的收益"<<endl;
for(int j=0;j<bagsNumber;j++)
{
cin>>benefit ;
bagsprofit.push_back(benefit);
}
cout<<endl;
Greedy greedy4(Weight,bagsweight,bagsprofit);
greedy4.Uint();
greedy4.profit ();
return 0;
}