贪心算法求解背包问题

(1)问题描述
给定几组数据,利用贪心算法的思想,将物品装入背包并使得其价值最大。
(2)实验步骤
① 计算每种物品单位重量的价值 Vi/Wi.
② 依贪心选择策略,将尽可能多的单位重量价值最高的物品装入背 包。
③ 若将这种物品全部装入背包后,背包内的物品总重量未超过 C, 则选择单位重量价值次高
的物品并尽可能多地装入背包。
④ 依此策略一直地进行下去,直到背包装满为止。
C++实现代码如下:

#include <iostream>
#include <algorithm>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct Thing{
	int weight;
	int value;
	float per_v;
};
bool cmp(Thing a,Thing b){
	return a.per_v>b.per_v;
}
int main(int argc, char** argv) {
	int n;
	cout<<"input the number of things:"<<endl;
	cin>>n;
	int c;
	cout<<"input the capacity of the bag:"<<endl;
	cin>>c;
	Thing things[n];
	for(int i=0;i<n;i++){
		cin>>things[i].weight;
		cin>>things[i].value;
		things[i].per_v=things[i].value/things[i].weight;
	}
	sort(things,things+n,cmp);
	for(int i=0;i<n;i++){
		cout<<things[i].weight<<" ";
	}
	cout<<endl;
	int i;
	float sum=0;
	for(i=0;i<n;i++){
		if(things[i].weight<=c){
			c-=things[i].weight;
			sum+=things[i].value;
			cout<<"价值"<<things[i].value<<"重量"<<things[i].weight<<"的物品装入背包"<<endl; 
		}else{
			break;
		}
	}
	if(i<n && c>0){
		float rate=(float)c/(float)things[i].weight;
		sum+=things[i].value*rate;
		cout<<"价值"<<things[i].value<<"重量"<<things[i].weight<<"的物品装入背包,"<<"装入比例:"<<rate<<endl; 
	}
	cout<<"装入背包物品总价值为:"<<sum<<endl;
	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值