贪心算法2:背包问题

背包问题

假设山洞中有n种宝物,每种宝物有一定重量w和相应价值v,毛驴运载能力有限,只能运走m重量的宝物,一种宝物只能拿一样,宝物可以分割,那么怎么才能使毛驴运走宝物的价值最大呢?

贪心策略:

(1)每次都拿最轻的一个,这样价值不一定最大,所以pass掉。

(2)每次都运走价值最大的一个,这样重量如果很重,价值总和不一定最大,所以pass掉;

(3)每次都运走单位价值最大的一个,这样就能使得毛驴运走的宝物最大

重点:宝物可以被分割。

算法设计:

#include<iostream>
#define MAXN 1000005
#include<algorithm>
using namespace std;
struct three{//类型一定要用double 
	double w;//每种宝物的重量 
	double v;//数量 
	double p;//单位价值即性价比 
}; 

three a[MAXN];
bool cmp1(three &a, three &b)
{
	return a.p > b.p;
}

int main()
{
	freopen("a.txt","r",stdin);
	int n, c;//n是数量,c是驴子的承载重量
	cin >> n >> c;
	double maxv = 0;
	double tmp = c;
	for(int i = 1; i <= n; ++i)
	{
		cin >> a[i].w >> a[i].v;
		a[i].p = a[i].v/a[i].w;
	}
	sort(a+1,a+1+n,cmp1);
	for(int i = 1; i <= n; ++i)
	{
		tmp -= a[i].w;//最后剩余的重量 
		if(tmp >= 0)
		{
			maxv += a[i].v;
		}
		else
		{
			tmp = tmp + a[i].w;
			maxv += tmp * a[i].p;
			break;//一定要加break,跳出循环 
		} 
	}
	cout << maxv << endl;
	return 0;
} 

 【注意】如果物品不能被分割,就不能采用贪心算法。

猜你喜欢

转载自blog.csdn.net/yanyanwenmeng/article/details/83008780