从贪心法、动态规划、回溯法、分支限界法谈背包问题————持续更新

贪心算法,(其实是很简单很简单的算法,就是排序然后按顺序取就完事)顾名思义,我们每次都要贪婪地得到最好的,但是既然是最好的肯定有个比较标准,体现在算法中也就是特定的排序函数,我们利用此排序函数对集合进行排序。接下来就是每次都从拍好序的集合中找到我们想要的。
在部分背包问题中,贪心算法不会像在0-1背包问题那样浪费任何容量。因此,总是能给出最优解。
代码如下:

/*
背包问题 贪心
不要忘记给结构体内变量赋初值
变量为double类型
*/
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;

struct ware {
	int num;//物品序号
	double P;//效益
	double W;//重量
	double p_w;//单位效益
	ware()
	{
		num = 0;
		P = 0.0;
		W = 0.0;
		p_w = 0.0;
	}
};
struct Bag {
	int num;//背包号码
	double weight;//重量(单位化)
	Bag() { num = 0; weight = 0.0; }
};

bool cmp(ware a, ware b)//从大到小排列
{
	return a.p_w > b.p_w;
}

int main()
{
	int n;
	double M;
	cin >> n >> M;

	vector<ware> W_P(n);//可以用变量值初始化

	for (int i = 0; i < n; i++)
	{
		//此种方式事前不必定义大小或大小随意
		ware temp;
		temp.num = i + 1;//背包号码
		cin >> temp.P >> temp.W;
		temp.p_w = temp.P / temp.W;
		W_P.push_back(temp);

		//当不会发生越界的时候可用此种方式
		/*
		cin >> W_P[i].P >> W_P[i].W;
		W_P[i].p_w = W_P[i].P / W_P[i].W;
		W_P[i].num = i + 1;
		*/
	}


	sort(W_P.begin(), W_P.end(), cmp);

	cout << "排好序的结果为:" << endl;
	for (int i = 0; i < n; i++)
	{
		cout << W_P[i].num << " " << W_P[i].p_w << endl;
	}

	vector<Bag> J(n);

	for (int i = 0; i < n; i++)
	{
		if (W_P[i].W < M)
		{
			M = M - W_P[i].W;
			J[i].num = W_P[i].num;
			J[i].weight = 1.0;
		}
		else {
			J[i].num = W_P[i].num;
			J[i].weight = M / W_P[i].W;
			break;
		}
	}

	int i = 0;
	cout << "背包问题最优结果为:" << endl;
	while (J[i].num != 0)
	{
		cout << J[i].num << " " << J[i].weight << endl;
		i++;
	}
	return 0;
}

在这里插入图片描述
动态规划
(其实动态规划也不难,真心不难)
如果可以证明最优性原理适用,就可以使用动态规划解决0-1背包问题。
最优性原理是指“

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值