X轴上有N条线段,每条线段包括1个起点和终点。线段的重叠是这样来算的,10201020和12251225的重叠部分为12201220。
给出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 <algorithm>
using namespace std;
struct stu{
int a,b;
}hh[50000];
bool map(stu x,stu y){
if(x.a!=y.a) return x.a<y.a;
else return x.b<y.b;
}
int main()
{
int n,k=0,ans=0;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d%d",&hh[i].a,&hh[i].b);
sort(hh,hh+n,map);
for(int i=0;i<n;i++)
{
if(hh[i].b>=hh[i-1].b) ans=max(ans,hh[i-1].b-hh[i].a);
else
{
ans=max(ans,hh[i].b-hh[i].a);
hh[i]=hh[i-1]; /*由已知可得hh[i].a>=hh[i-1].a,hh[i].b<hh[i-1].b;所以线段i含于线段i-1,因为求的
} 是最长距离,所以把i-1赋值给i */
}
printf("%d\n",ans);
return 0;
}