【算法】贪心算法:背包问题

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值