贪心算法

 加勒比海盗船-最优装载问题

#include<iostream>
#include<algorithm>
const int N = 1000005;
using namespace std;
double w[N];//古董的重量数组
int main()
{
	double c;
	int n;
	cout<<"请输入载重量c及古董个数:"<<endl;
	cin>>c>>n;
	cout<<"请输入每个古董的重量:"<<endl;
	for(int i=0;i<n;i++)
	{
		cin>>w[i];//输入每个物品重量
	}
	sort(w,w+n);//按古董重量升序排序
	double temp=0.0;
	int ans=0;//tmp为已装在到船上的古董重量,ans为古董个数
	for(int i=0;i<n;i++)
	{
		tmp+=w[i];
		if(tmp<c)
			ans ++;
		else
			break;
	}
	cout<<"能装入的古董最大数量为Ans=";
	cout<<ans<<endl;
	return 0;
}

阿里巴巴于是四大盗--背包问题

#include<iostream>
#include<algorithm>
using namespace std;
const int M=10000005;
struct three{
	double w;//每个宝物的重量
	double v;//每个宝物的价值
	double p;//性价比
}s[M];
bool cmp(three a,three b)
{
	return a.p>b.p;
}
int main()
{
	int n;
	double m;
	cout<<"请输入宝物数量n及毛驴的承载能力:<<endl;
		cin>>n>>m;
	cout<<"请输入每个宝物的重量和价值,用空格分开:<<ebdl;
		for(int i=0;i<n;i++)
		{
			cin>>s[i].w>>s[i.v;
			s[i].p=s[i].v/s[i].w;
		}
		sort(s,s+n,cmp);
		double sun=0.0;
		for(int i=0;i<n;i++)
		{
			if(m>s[i].w)
			{
				m-=s[i].w;
				sum+=s[i].v;
			}
			else
			{
				sum+=m*s[i].p;
				break;
			}
		}
		cout<<"装入宝物的最大价值Maximum value="<<sum<<endl;
		return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值