最大相容活动子集合 贪心法

 主要学习sort的用法和贪心法

测试例:

11
1 4
3 5
5 7
0 6
3 8
5 9
8 11
6 10
8 12
2 13
12 14


#include <iostream>
#include <algorithm>		//sort函数的头文件
using namespace std;
struct action{
	int s;		//起始时间
	int f;		//终止时间
	int index;	//活动编号
};
action a[1010];
int n;

//把const去掉也不报错
bool comp(const action &a,const action &b)
{
    return a.f <= b.f ? true: false;
}
int forjob() 
{
    int num = 1;			//第一个活动是必选
	sort(a, a + n, comp);	//根据终止时间排序
    int temp = 0;
	cout<<a[0].index;
    for(int i = 1; i < n; i++){
		//如果当前活动的开始时间在上一个被选活动结束之后开始
        if(a[i].s >= a[temp].f){
			num++;
            temp = i;
			cout<<" "<<a[temp].index;
        }
    }
	cout<<endl;
    return num;
}

int main()
{
    //freopen("in.txt", "r", stdin);
    int i = 0;
	cin>>n;
	for(i = 0; i < n; i++){
		cin>>a[i].s>>a[i].f;
		a[i].index = i;
	}
    forjob();
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值