基准时间限制: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
思路:将线段a[]按左端点从大到小排序,再将所有线段放入 优先队列Q(线段右端点大的优先级高(先出队列))。
遍历所有线段a[]:首先将已经遍历的线段标记,在判断Q.top()是否已经标记,若已标记则出队列。这样能保证队列中的线段的左端点都比当前线段的左端点小,从而只要找到队列中线段最大的右端点(也就是Q.top())即为当前线段的最大重叠。最后比较各线段的最大重叠即为线段的最大重叠。
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int MAX_N=50005;
struct node{
int id;
int l;
int r;
bool operator<(const node &x){
return l>x.l;
}
}a[MAX_N];
int n,ans;
bool book[MAX_N];
bool operator<(const node &x,const node &y){
return x.r<y.r;
}
priority_queue<node> Q;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n;
for(int i=0;i<n;++i)
{
cin>>a[i].l>>a[i].r;
a[i].id=i;
Q.push(a[i]);
}
sort(a,a+n);
for(int i=0;i<n-1;++i)
{
book[a[i].id]=true;
while(!Q.empty()&&book[Q.top().id]==true){
Q.pop();
}
if(Q.empty()) break;
if(Q.top().r>a[i].r) ans=max(ans,a[i].r-a[i].l);
else ans=max(ans,Q.top().r-a[i].l);
}
cout<<ans<<endl;
return 0;
}