0
点赞
收藏
分享

微信扫一扫

51nod 1091 线段的重叠 (贪心)


https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1091


1091 线段的重叠



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




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



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



Input示例



5
1 5
2 4
2 8
3 7
7 9



Output示例



4


被水侮辱了!!!。

按左端点升序。只需记录已经扫过的最大右端点,和当前左端点作差

【代码】:


#include <iostream>  
#include <algorithm> 
using namespace std;
struct node{
	int l,r;
}a[50101];
bool cmp(node a,node b)
{
	return a.l<b.l;
}
int main()
{
	int n;
	while(cin>>n)
	{
		for(int i=1;i<=n;i++)
		{
			cin>>a[i].l>>a[i].r;
		}
		sort(a+1,a+1+n,cmp);
		int ans=0,pre=0;
		for(int i=1;i<=n;i++)
		{
			ans=max(ans,min(pre,a[i].r)-a[i].l);
			if(pre<a[i].r)
				pre=a[i].r;
		}
		cout<<ans<<endl;
	}
}




举报

相关推荐

0 条评论