线段线段 51Nod - 1091 (贪心)

X轴上有N条线段,每条线段包括1个起点和终点。线段的重叠是这样来算的,[10 20]和[12 25]的重叠部分为[12 20]。

给出N条线段的起点和终点,从中选出2条线段,这两条线段的重叠部分是最长的。输出这个最长的距离。如果没有重叠,输出0。

Input

第1行:线段的数量N(2 <= N <= 50000)。 
第2 - N + 1行:每行2个数,线段的起点和终点。(0 <= s , e <= 10^9)

Output

输出最长重复区间的长度。

Sample Input

5
1 5
2 4
2 8
3 7
7 9

Sample Output

4

贪心的题目确实不好写(对于弱鸡的我来说

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[56];
struct nomd
{
	int x,y,t;
}p[50006];
int cmp1(nomd a,nomd b)
{
	if(a.x!=b.x)
	return a.x<b.x;
	return a.y>b.y;
}

int main()
{
	
	
	int n,m;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
		scanf("%d %d",&p[i].x,&p[i].y);
	
	}
	sort(p,p+n,cmp1);
	int maxn=0;int a=0,b=0;
	int ans=0;
	for(int i=1;i<n;i++)
	{
	
		if(p[i].y<=p[a].y)//区间覆盖
		{
			ans=p[i].y-p[i].x;
			maxn=max(maxn,ans);
		}
		else//没覆盖和不相交
		{
			ans=p[a].y-p[i].x;
			maxn=max(maxn,ans);
			a=i;
		}
	}
	printf("%d\n",maxn);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/liuliu2333/article/details/81390968
今日推荐