#include <iostream>
#include <algorithm>
#define MAX_NUM 1000
using namespace std;
struct Goods //info of goods定义物品信息结构体
{
int weight;// 物品重量
int value;// 物品价值
double ValPerWei;// 物品单位重量的价值
double load; //物品装入背包的部分数目,为0-1之间
};
int cmp( Goods const &a, Goods const &b)//定义sort函数的比较函数
{
if(a.ValPerWei < b.ValPerWei) return 0;
else return 1;
}
void Greedy(Goods g[],int good_num, int content)//贪心算法
{
for(int i=0; i < good_num; i++)
{
if(content > g[i].weight)//如果背包足够装下整个物品
{
content -= g[i].weight;
g[i].load = 1;
}
else if(content > 0){//如果背包不足以装下整个物品
g[i].load = (double)content/g[i].weight; //计算物品装入背包的部分
content= 0; //背包容量置0
return; //程序结束,返回
}
}
}
int main()
{
int goods_num;
int bagvol;
double total_value=0;
double total_weight=0;
cout << "请输入背包的容量:" << endl;
cin >> bagvol;
cout << "请输入物品的数量:" << endl;
cin >> goods_num;
Goods G[goods_num+1];
cout << "请依次输入物品的重量和价值:" << endl;
for(int i=0; i<goods_num; i++)
{
cin>> G[i].weight >> G[i].value;//输入重量价值
G[i].ValPerWei = (double)G[i].value/G[i].weight;//计算权重
G[i].load = 0;//load置0
}
sort (G, G+goods_num,cmp);//sort by ValPerWei
Greedy(G, goods_num,bagvol);
cout<<"背包中的物品:"<<endl;
for(int i=0;i<goods_num;i++)//output the info of goods
{
if(G[i].load==0.0)break;//如果检测到物品未被装入背包,则推出循环
total_value+=(G[i].value*G[i].load);//装入背包的物品总价值
total_weight+=(G[i].weight*G[i].load);//装入背包的物品总重量
cout << "重量: " << G[i].weight << " "<<"价值: "<<G[i].value<<" "<<endl;
cout << "单位重量的物品价值: "<<G[i].ValPerWei << endl;
cout << "装入物品部分: "<<G[i].load<<endl;//输出装入背包的物品信息
cout << "*************************" << endl;
}
cout<<"背包容量: "<<bagvol<<endl;
cout<<"装入物品总重量: "<<total_weight<<endl;
cout<<"装入物品总价值: "<<total_value<<endl;
}
【算法】贪心算法:背包问题
最新推荐文章于 2024-08-04 17:55:35 发布