洛谷 P1803 凌乱的yyy / 线段覆盖


经典排序贪心

开始时间从小到大为第一关键字

结束时间从大到小为第二关键字

从尾至头连一遍输出结果

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

const int MAXN = 1e6 + 10;

struct ctst
{
	int beg, end;
}arr[MAXN];
 
bool cmp(ctst a, ctst b)
{
	if(a.beg != b.beg)
		return a.beg < b.beg;
	return a.end < b.end;
}

int main()
{
	int n;
	cin>>n;
	
	for(int i = 0; i < n; i++)
		cin>>arr[i].beg>>arr[i].end;
		
	sort(arr, arr + n, cmp);
	
	int ans = 1, rbeg = arr[n - 1].beg;
	
	for(int i = n - 2; i >= 0; i--)
	{
		if(arr[i].end <= rbeg)
		{
			rbeg = arr[i].beg;
			ans ++;
		}
	}
		
	cout<<ans<<endl;
	
	return 0;
}


猜你喜欢

转载自blog.csdn.net/zeolim/article/details/81019079
今日推荐