贪心法解决背包问题

 背包问题

问题描述:给定n 种物品和一个容量为C的背包,物品i的重量是wi,其价值为vi,背包问题是如何选择装入背包的物品,使得装入背包中物品的总价值最大。注意:和0/1背包问题的区别,在背包问题中,可以将某种物品的一部分装入背包中,但不可重复装入。

提示:用贪心算法求解背包问题的关键是如何选择贪心策略,使得按照一定的顺序选择每个物品,并尽可能的装入背包,直到装满。至少有三种贪心策略:

(1) 选择价值最大的物品,因为这可以尽可能快地增加背包的总价值。

(2) 选择重量最轻的物品,因为这可以装入尽可能多的物品。

(3) 选择单位重量价值最大的物品

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct Thing {
	int weight, value;
	double need;
};
vector<Thing> bags = { {20,60},{30,120},{10,50} };
template<typename func>
int judge(vector<Thing*> vc, const func& cmp,int size) {
	int v = 0;
	sort(vc.begin(), vc.end(), cmp);
	for (auto& it : vc) {
		if (it->weight <= size) {
			it->need = 1;
			v += it->value;
			size -= it->weight;
		}
		else {
			it->need = size /(double) it->weight;
			v += it->value * it->need;
			break;
		}
	}
	for (int i = 0; i < bags.size(); i++) 
		cout << "第" << i + 1 << "件物品要放:" << bags[i].need << endl;
	return v;
}
int main() {
	vector<Thing*> vc;
	/*cout << "输入 物品重量及价值,键入Ctrl + z结束:" << endl;
	do {
		cin >> w >> v;
		bags.push_back({ w,v });
	} while (!cin.eof());*/
	for (auto& it : bags)
		vc.push_back(&it);
	int v, w;
	int size = 50;
	auto maxValue = [](auto & a, auto & b) {return a->value > b->value; };
	auto minWeight = [](auto & a, auto & b) {return a->weight < b->weight; };
	auto maxCmp = [](auto & a, auto & b) {return a->value / (double)a->weight > b->value / (double)b->weight; };
	cout << "----------------第一种算法(价值最大):" << endl;
	cout << judge(vc, maxValue, size) << endl;
	cout << "----------------第二种算法(重量最轻):" << endl;
	cout << judge(vc, minWeight, size) << endl;
	cout << "----------------第三种算法(单位重量价值最大):" << endl;
	cout << judge(vc, maxCmp, size) << endl;
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值