贪心算法(算法分析与设计)

1.活动安排问题

使剩余安排时间极大化

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
struct Node
{
	int s;
	int f;
};
bool cmp(Node a,Node b)
{
	return a.f<b.f;
}
int greedySelector(vector<Node> &x,vector<bool> &a)
{
	int n=x.size()-1;
	int j=0;
	int count=1;
	a[0]=true;
	for(int i=1;i<=n;i++)
	{
		if(x[i].s>=x[j].f)
		{
			a[i]=true;
			j=i;
			count++;
		}
		else
		{
			a[i]=false;
		}
	} 	
	return count;
}
int main()
{
	vector<Node> n;
	vector<bool> a;
	int num;
	cin>>num;
	for(int i=0;i<num;i++)
	{
		Node temp;
		cin>>temp.s>>temp.f;
		n.push_back(temp);
		a.push_back(false);
	}
	sort(n.begin(),n.end(),cmp);
	cout<<greedySelector(n,a)<<endl;
	return 0;
}

2.最优装载

#include<iostream>
#include<vector>
#include<algorithm>
#include<cstdlib>
using namespace std;
struct Node
{
	double w;
	int i;
};
bool cmp(Node a,Node b)
{
	return a.w<b.w;
}
double random(int start,int end)
{
	return (start+rand()%(end-start)+0.0)/10;
}
int loading(vector<Node> &x,vector<int> &a,double c)
{
	int i=0;
	while(i<x.size())
	{
		if(x[i].w<=c)
		{
			c=c-x[i].w;
			a.push_back(x[i].i);
			i++;	
		}
		else
		{
			break;
		}
	}
	return i;
}
int main()
{
	vector<Node> n;
	vector<int> a;
	int num;
	double c;
	cin>>num>>c;
	for(int i=0;i<num;i++)
	{
		Node temp;
		temp.w=random(1,2000);
		temp.i=i;
		n.push_back(temp);
		cout<<"n["<<i<<"]: "<<temp.w<&
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值