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
对于所有线段,我们以起点升序,终点降序排一遍序。
然后O(N)遍历,每次只取区间宽度最长的边(起点一样,终点最远)。
有一个tmp记录每次比较完更新的边。
例如:
1 5
2 4
2 8
3 7
7 9
1 5
2 8
2 4
3 7
7 9
tmp先记录1,5,比较完(2,4)更新成(2,5)一直这样下去即可。
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cctype>
#include<cmath>
#include<ctime>
#include<string>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#include<set>
#include<map>
#include<cstdio>
#include<limits.h>
#define MOD 1000000007
#define fir first
#define sec second
#define fin freopen("/home/ostreambaba/文档/input.txt", "r", stdin)
#define fout freopen("/home/ostreambaba/文档/output.txt", "w", stdout)
#define mes(x, m) memset(x, m, sizeof(x))
#define Pii pair<int, int>
#define Pll pair<ll, ll>
#define INF 1e9+7
#define inf 0x3f3f3f3f
#define Pi 4.0*atan(1.0)
#define lowbit(x) (x&(-x))
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
typedef long long ll;
typedef unsigned long long ull;
const double eps = 1e-9;
const int maxn = 50000+10;
const int maxm = 205;
using namespace std;
inline int read(){
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
return x*f;
}
struct line{
int l,r;
}p[maxn];
bool operator<(const line&a,const line&b){
if(a.l==b.l){
return a.r>b.r;
}else{
return a.l<b.l;
}
}
int main(){
int n=read();
for(int i=0;i<n;++i){
p[i].l=read(),p[i].r=read();
}
int ans=0;
sort(p,p+n);
line tmp=p[0];
for(int i=1;i<n;++i){
if(p[i].l==p[i-1].l){
continue;
}
if(p[i].r<tmp.r){
ans=max(ans,p[i].r-p[i].l);
}else{
ans=max(ans,tmp.r-p[i].l);
tmp.r=p[i].r;
}
tmp.l=p[i].l;
}
cout<<ans<<endl;
return 0;
}