Description
They are N segments in x-axis, each segment has a start point X, a end point Y, so it can express as [X, Y].
Now you should select two segments, they have the longest overlap length.
Segment [3, 10] and segment [7, 12] overlap in [7, 10], so the length is 3.
Input Description
The first line is case number T( T <= 10 ).
For each case, the first line is the segment number N( 1 <= N <= 100,000 ), then follow N line, each line contian Xi and Yi.( 0 <= Xi < Yi < 100,000 )
For each case, the first line is the segment number N( 1 <= N <= 100,000 ), then follow N line, each line contian Xi and Yi.( 0 <= Xi < Yi < 100,000 )
Output Description
The longest overlap length of any two segments.
Sample Input
1 5 1 5 2 4 2 8 3 7 7 9
Sample Output
4
哎。如此水的一道题。我当时既然做不出来。。。。先按边起点从小到大排序,终点也从小到大排序。注意每条边都要喝前面的终点最右的边进行比较。
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
inline int max(int a,int b)
{
return a>b?a:b;
}
struct Edge
{
int from,to;
}edge[100008];
bool cmp(Edge a,Edge b)
{
if(a.from<b.from)return 1;
if(a.from>b.from)return 0;
if(a.from==b.from)
{
if(a.to>b.to)return 0;
else return 1;
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d%d",&edge[i].from,&edge[i].to);
}
sort(edge+1,edge+n+1,cmp);
int s=edge[1].from,t=edge[1].to;
int maxlen=0;
for(int i=2;i<=n;i++)
{
if(edge[i].from<t)
{
if(edge[i].to<=t)
{
maxlen=max(maxlen,edge[i].to-edge[i].from);
}
else
{
maxlen=max(maxlen,t-edge[i].from);
s=edge[i].from;
t=edge[i].to;
}
}
else continue;
}
printf("%d\n",maxlen);
}
return 0;
}