51Nod-1091-线段的重叠

来源:互联网 发布:http 文件 json 上传 编辑:程序博客网 时间:2024/06/16 06:52


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示例
51 52 42 83 77 9
Output示例
4

51Nod-1091-线段的重叠

思路:将线段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);elseans=max(ans,Q.top().r-a[i].l);}cout<<ans<<endl;return 0;}

原创粉丝点击