用贪心算法解决背包问题(物品可分割)
来源:互联网 发布:windows是应用软件吗 编辑:程序博客网 时间:2024/04/30 11:05
#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;
}
- 用贪心算法解决背包问题(物品可分割)
- 背包问题(物品可分解)--贪心算法
- 贪心法求解背包问题(部分背包 物品可分)
- NYOJ - 106 - 背包问题(物品可分割问题)
- 贪心法之可分割背包问题
- 贪心法求解背包问题(物品可分)
- 背包问题(背包可划分)贪心算法
- 贪心算法实现背包问题(背包可拆分)
- 用贪心算法解决背包问题
- 物品无限的背包问题(贪心算法) By ACReaper
- 可拆分物品背包问题
- 贪心算法解决背包问题
- 贪心算法解决背包问题
- 贪心算法解决背包问题
- 背包问题(物体可分割)
- 用贪心算法解决0-1背包问题
- 贪心算法解决部分背包问题
- 数据结构(C#)-- 贪心算法解决背包问题
- 2009年全国数模比赛,江苏三等奖名单
- 键盘控制运动
- CreateThread、_beginthreadex和AfxBeginThread分析
- 谈话过后
- Sql语句~1
- 用贪心算法解决背包问题(物品可分割)
- 母牛的故事
- MyEclipse 6.5 下载及注册
- Ubuntu 9.04安装arm-linux-gcc交叉编译工具
- JavaScript
- [初级理论]给老婆做测试培训-06
- 1602字符液晶
- 数组与结构体
- MyEclipse 6.5