D - 线段线段

部分为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

此题有个坑点,就是不仔细想很可能直接就相邻两项去比较,这样就只能wa了,由于题中明确要求最长重复的区间,所以可以先对终点进行降序,如果终点相同则对起点进行降序排列。代码如下:

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#define ll long long
struct point{
    ll x,y;//结构体:起点为x终点为y;
}p[50050];
bool cmp(point a,point b ){
    if(a.y==b.y){
        return a.x>b.x;
    }
    return a.y>b.y;//对数组进行排序;
}
int main(){
    ll a,b,c,i,sum;
    scanf("%lld",&a);
    for(i=0;i<a;i++){
        scanf("%lld%lld",&p[i].x,&p[i].y);
    }
    sort(p,p+a,cmp);
    sum=0;
    b=p[0].x;//以第一个点为起点进行比较;
    for(i=1;i<a;i++){
        if(p[i].x <=b){
            sum=max(sum,p[i].y-b);
            b=p[i].x;//取最大区间长度;

        }
        else{
            sum=max(sum,p[i].y-p[i].x);
        }
    }
    if(sum==0){
        printf("%d\n",0);
        return 0;
    }

    printf("%lld\n",sum);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/liubang00001/article/details/81364123