[贪心][51nod] 1133 不重叠的线段

 

1133 不重叠的线段 

基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题

 收藏

 关注

X轴上有N条线段,每条线段有1个起点S和终点E。最多能够选出多少条互不重叠的线段。(注:起点或终点重叠,不算重叠)。

例如:[1 5][2 3][3 6],可以选[2 3][3 6],这2条线段互不重叠。

Input

第1行:1个数N,线段的数量(2 <= N <= 10000)
第2 - N + 1行:每行2个数,线段的起点和终点(-10^9 <= S,E <= 10^9)

Output

输出最多可以选择的线段数量。

Input示例

3
1 5
2 3
3 6

Output示例

2

 

贪心算法 

1.尾降序排序 

2.线段长升序排序

 

#include <iostream>
#include <algorithm>
using namespace std;
struct lines
{
	long long fst, lst;
}arr[10010];
bool cmp(lines x, lines y)
{
	if(x.lst != y.lst)
		return x.lst < y.lst;
	else
		return x.fst < y.fst;
}
int main()
{
	int n;
	cin>>n;
	for(int i = 0; i < n; i++)
	{
		cin>>arr[i].fst>>arr[i].lst;
	}
	sort(arr, arr + n, cmp);
	long long end = - 1e11, ans = 0;
	for(int i = 0; i < n; i++)
	{
		if(arr[i].fst >= end)
		{
			ans ++;
			end = arr[i].lst;
		}
	}
	cout<<ans<<endl;
	return 0;
}

 

 

 

posted @ 2018-05-08 17:08  张浦  阅读(88)  评论(0)    收藏  举报