[蓝桥杯] 管道 java题解

import java.util.*;

/**
 * 管道
 * 其实这道题核心根本不用管管道左边的如何,我们可以把左边当成注水口
 */
public class Main {
    static int n;
    static int[][] pipes ;  // 阀门安排的地方
    static int len;  // 管道长度
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        len = sc.nextInt();
        pipes = new int[n][2];
        for (int i = 0; i < n; i++) {
            pipes[i][0] = sc.nextInt();  //阀门打开位置
            pipes[i][1] = sc.nextInt();  //阀门打开时间
        }
        // 二分法求时间
        int l=0,r=Integer.MAX_VALUE;
        while(l<=r){
            int mid = (l+r)>>1;
            if(check(mid)){  //时间可能大了
                r = mid - 1;
            }else{  // 时间小了
                l = mid + 1;
            }
        }
        System.out.println(l);
    }
    public static boolean check(int time){
        int rightLast = 0;
        for (int i = 0; i < n; i++) {
            if(pipes[i][1]<= time){  // 在该阀门打开时间这个时间段内
                int l = pipes[i][0] - ( time-pipes[i][1] );
                int r = pipes[i][0] + ( time-pipes[i][1] );
                // 只要左区间在右边囊括的范围内或者正好挨边就提取最右边的区间
                if(l<=rightLast+1) rightLast = Math.max(r,rightLast);
            }
        }
        return rightLast>=len;
    }
}

posted @ 2024-03-31 16:35  XFS小风  阅读(41)  评论(1)    收藏  举报