参考大佬代码:(区间合并+二分)
import os
import sys
n, L = map(int, input().split()) # 输入n,len
arr = [list(map(int, input().split())) for _ in range(n)] # 输入Li,Si
def check(Ti, arr, L)->bool:
sec = [] # 存入已打开的阀门在Ti时刻能检测到水流的管道区间
for Li, Si in arr: # 遍历已打开的阀门,计算存入能检测到水流的管道区间
if Ti >= Si:
sec.append((Li - (Ti-Si), Li + (Ti-Si)))
sec.sort()
if not sec or sec[0][0] > 1:
return False
rboundary = sec[0][1] # 初始化最大右边界
for i in range(1, len(sec)): # 遍历管道区间并合并相邻区间
if sec[i][0] - rboundary <= 1:
rboundary = max(rboundary, sec[i][1])
else:
break
return rboundary >= L
l,r = 0,10**9
while l < r: # 二分
mid = (l + r) // 2
if check(mid, arr, L):
r = mid
else:
l = mid + 1
print(l)