蓝桥杯管道 -- 二分, 区间覆盖

蓝桥杯管道 -- 二分, 区间覆盖

原题链接

参照执梗大佬的代码, 我太菜了wuwuwu......

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

/**
 * ClassName:Main12
 * Package:
 * Description:
 *
 * @author:LH寒酥
 * @create:2023/11/15-20:22
 * @version:v1.0
 */
public class Main {
    static int n, m;

    static boolean check(long mid, int[] a, int[] s) {
        List<long[]> list = new ArrayList<>();
        for (int i = 0; i < n; i ++) {
            if (mid >= s[i])
                list.add(new long[] {a[i] - (mid - s[i]), a[i] + (mid - s[i])});
        }
        Collections.sort(list, (o1, o2) -> Long.compare(o1[0], o2[0]));

        if (list.size() == 0) return false;
        long[] arr = list.get(0);
        if (arr[0] > 1) return false;

        long r = arr[1];
        for (int i = 1; i < list.size(); i ++) {
            long[] temp = list.get(i);
            if (temp[0] <= r + 1) r = Math.max(r, temp[1]);
            else break;
        }

        return r >= m;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        int[] a = new int[n];
        int[] s = new int[n];
        for (int i = 0; i < n; i ++) {
            a[i]= sc.nextInt();
            s[i]= sc.nextInt();
        }
        long l = 0, r = (int)1e9 + 1;
        while (l + 1 < r) {
            long mid = l + r >> 1;
            if (check(mid, a, s)) r = mid;
            else l = mid;
        }
        System.out.println(r);
    }
}

posted @ 2023-11-15 20:44  LH寒酥  阅读(29)  评论(1编辑  收藏  举报