欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

51nod--1091 线段的重叠

程序员文章站 2022-07-05 14:18:43
...

题目描述


基准时间限制: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


解题思想


/*
设边的开头为start,结尾为end,思路:
先对start升序排,如果start相等,则把end降序排
,这样排完之后,无非有2种情况,一种是包含,一种是
有重叠,自己画个图就明白了。
*/

代码


import java.util.Scanner;
import java.util.Arrays;
import java.util.Comparator;
public class Main{
    private static class Duan{
        int start ;
        int end ;
        public Duan(int s, int e){
            start = s;
            end = e;
        }
    }
    public static  class Mycompare implements Comparator<Duan>{

        @Override
        public int compare(Duan o1, Duan o2) {
            if(o1.start < o2.start)
                return -1;
            return 1;
        }

    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        //init
        int max = 0;
        Duan[] a = new Duan[n] ;
        for(int i=0; i<n; ++i)
           a[i] = new Duan(sc.nextInt(), sc.nextInt());
        //process
        Arrays.sort(a,new Mycompare());
        Duan s = a[0];
        for(int i=1; i<n; ++i){
        //包含在内
            if(s.end>=a[i].end)
                max = Math.max(max, a[i].end-a[i].start);
                //重叠
            else if(s.end>=a[i].start && s.end<a[i].end){
                max = Math.max(max, s.end-a[i].start);
                s = a[i];
            }
        }
        //output
        System.out.println(max);
    }
}
相关标签: 算法 91