51NOD 1091

Problem : 线段的重叠

Description :

X轴上有N条线段,每条线段包括1个起点和终点。线段的重叠是这样来算的,[10 20]和[12 25]的重叠部分为[12 20]。
给出N条线段的起点和终点,从中选出2条线段,这两条线段的重叠部分是最长的。输出这个最长的距离。如果没有重叠,输出0。

Solution :

贪心。按线段的左端点升序排序,然后扫描一遍,利用线段的右端点维护一个最大值,与当前线段的左右端点比较一下就可以得到答案。

Code(JAVA) :

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class Main {

    Scanner cin = new Scanner(System.in);

    Main() {
        while (cin.hasNext()) {
            int n = cin.nextInt();
            Line[] lines = new Line[n];
            for (int i = 0; i < n; i++)
                lines[i] = new Line(cin.nextInt(), cin.nextInt());

            Arrays.sort(lines, new Comparator<Line>() {
                @Override
                public int compare(Line A, Line B) {
                    return A.x - B.x;
                }
            });

            int curMax = lines[0].y, ans = 0;
            for (int i = 1; i < n; i++) {
                if (curMax <= lines[i].x) {
                    curMax = lines[i].y;
                    continue;
                }
                ans = Math.max(ans, Math.min(curMax, lines[i].y) - lines[i].x);
                curMax = Math.max(lines[i].y, curMax);
            }

            System.out.println(ans);
        }
    }

    public static void main(String[] args) {
        new Main();
    }
}

class Line {
    Line () {

    }

    Line(int x, int y) {
        if (x > y) {
            int tmp = x;
            x = y;
            y = tmp;
        }
        this.x = x;
        this.y = y;
    }

    int x, y;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值