贪婪算法解决背包问题

阅读《算法的乐趣》第3章的贪婪算法部分时,看到书上利用贪婪算法解决背包问题:

假设我们有n件物品,分别编号为1, 2...n。其中编号为i的物品价值为vi,它的重量为wi。为了简化问题,假定价值和重量都是整数值。现在,假设我们有一个背包,它能够承载的重量是W。现在,我们希望往包里装这些物品,使得包里装的物品价值最大化,那么我们该如何来选择装的东西呢?


书上写了几个重要的结构体和处理函数,这里我把程序补充完整,并且运行成功了。

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

typedef int SELECT_POLICY;

typedef struct tagObject{
	int weight = 0;
	int price = 0;
	int status = 0;
}OBJECT;

typedef struct tagKnapSackProblem{
	vector<OBJECT> objs;
	int totalC;
}KNAPSACK_PROBLEM;

void PrintResult(vector<OBJECT>& objs){
	for (int i = 0; i < static_cast<int>(objs.size()); i++)
	{
		if (objs[i].status == 1){
			cout << (i+1) << " ";
		}
	}
	cout << endl;
}

void GreedyAlgo(KNAPSACK_PROBLEM *problem, SELECT_POLICY spFunc(vector<OBJECT>&, int)){
	int idx;
	int ntc = 0;

	while ((idx = spFunc(problem->objs, problem->totalC - ntc)) != -1){

		if ((ntc + problem->objs[idx].weight) <= problem->totalC){
			problem->objs[idx].status = 1;
			ntc += problem->objs[idx].weight;
		}
		else{
			problem->objs[idx].status = 2;
		}
	}
	PrintResult(problem->objs);
}
//根据价值选取的贪婪算法
int Choosefunc1(vector<OBJECT>& objs, int c){
	int index = -1;
	int mp = 0;
	for (int i = 0; i<static_cast<int>(objs.size()); i++){
		if ((objs[i].status == 0) && (objs[i].price>mp)){
			mp = objs[i].price;
			index = i;
		}
	}

	return index;
}
//根据重量选取的贪婪算法
int Choosefunc2(vector<OBJECT>& objs, int c){
	int index = -1;
	int mp = INT_MAX;
	for (int i = 0; i < static_cast<int>(objs.size()) ; i++)
	{
		if ((objs[i].status==0)&&(objs[i].weight<mp))
		{
			mp = objs[i].weight;
			index = i;
		}
	}

	return index;
}
//根据价值密度选取的贪婪算法
int Choosefunc3(vector<OBJECT>& objs, int c){
	int index = -1;
	int mp = 0;
	
	for (int i = 0; i < static_cast<int>(objs.size()); i++)
	{
		double pricePerWeight = 1.0 *objs[i].price / objs[i].weight;
		if ((objs[i].status == 0) && (pricePerWeight > mp))
		{
			mp = pricePerWeight;
			index = i;
		}
	}
	return index;
}

int main(){
	OBJECT initObject;
	KNAPSACK_PROBLEM problem = { { initObject, initObject, initObject, initObject, initObject, initObject, initObject }, 150 };
	KNAPSACK_PROBLEM *problemNow = &problem;

	for (int i = 0; i < 7; i++)
	{
		cin >> problemNow->objs[i].weight >> problemNow->objs[i].price >> problemNow->objs[i].status;
		cout << problemNow->objs[i].weight << "	" << problemNow->objs[i].price << "	" << problemNow->objs[i].status << endl;
	}
	GreedyAlgo(problemNow, Choosefunc3);
	return 0;
}

当然,书上也提了,0-1背包问题的正确最优结果应该用动态规划来求得,我还需要进一步看书学习。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值