一、第一题:挤牛奶
解题思路:区间合并
区间合并模板题
【Python程序代码】
n = int(input())
a = []
for i in range(n):
l,r = map(int,input().split())
a.append([l,r])
def cmp(x):
return x[0],x[1]
a.sort(key=cmp)
res1,res2=0,0
st,ed = a[0][0],a[0][1]
for i in range(n):
if a[i][0]>ed:
res1 = max(res1,ed-st)
if st:res2 = max(res2,a[i][0]-ed)
st,ed = a[i][0],a[i][1]
else:
ed = max(ed,a[i][1])
res1 = max(res1,ed-st)
print(res1,res2)
二、第二题:区间合并
解题思路:区间合并
区间合并模板题
【Python程序代码】
n = int(input())
a = []
for i in range(n):
l,r = map(int,input().split())
a.append([l,r])
def cmp(x):
return x[0],x[1]
a.sort(key=cmp)
res = 0
ed = -1e9-1
for i in range(n):
if a[i][0]>ed:
res += 1
ed = a[i][1]
else:
ed = max(ed,a[i][1])
print(res)
三、第三题:校门外的树
解题思路:区间合并
区间合并模板题
【Python程序代码】
L,m = map(int,input().split())
a = []
for i in range(m):
l,r = map(int,input().split())
a.append([l,r])
def cmp(x):
return x[0],x[1]
a.sort(key=cmp)
st,ed = 0,0
res = 0
for i in range(m):
if a[i][0]>ed:
if ed:
res += ed - st + 1
st = a[i][0]
ed = a[i][1]
else:
ed = max(ed,a[i][1])
res += ed-st +1
print(L+1-res)
四、第四题:管道
解题思路:区间合并+二分
用二分优化采用区间合并判断是否符合条件,这题在之前的二分习题里面写过了,直接见代码。
【Python程序代码】
n,L = map(int,input().split())
a = []
for i in range(n):
l,r = map(int,input().split())
a.append([l,r])
def cmp(x):
return x[0],x[1]
a.sort(key=cmp)
def ck(mid):
tp = []
for i in range(n):
if a[i][1]<=mid:
tp.append([ a[i][0]-(mid-a[i][1]), a[i][0]+(mid-a[i][1]) ])
tp.sort(key=cmp)
ed = 0
for i in range(len(tp)):
if tp[i][0]>ed+1:return False
else:ed = max(ed,tp[i][1])
if ed>=L:return True
return False
l,r = 1,2000000000
while l<r:
mid = l+r>>1
if ck(mid):r=mid
else:l=mid+1
print(r)