【算法】 区间合并(附蓝桥杯真题) python

步骤

1.先将所有区间按左端点排序

2.从前往后扫一遍,维护当前正在合并的区间[st, ed]

3.依次检查每个区间[l, r]

l > ed,将[st, ed]加入 ans , 更新st = l,ed = r

l <= ed ,更新ed = max(ed, r)

时间复杂度 O(nlogn)


模板

https://www.acwing.com/problem/content/description/424/

code:

python 复制代码
l, m = map(int, input().split())  
grid = [list(map(int, input().split())) for _ in range(m)]  
grid.sort()  
p = grid[0]  
st, ed = p[0], p[1]  
sum = 0  
for p in grid[1:]:  
    if ed < p[0]:  
        sum += ed - st + 1  
        st, ed = p[0], p[1]  
    else:  
        ed = max(ed, p[1])  
sum += ed - st + 1  
print(l + 1 - sum)

小试牛刀

https://www.acwing.com/problem/content/1345/

code:

python 复制代码
n = int(input())  
grid = [list(map(int, input().split())) for _ in range(n)]  
grid.sort()  
p = grid[0]  
st, ed = p[0], p[1]  
ans, res = 0, 0  
for p in grid[1:]:  
    if ed < p[0]:  
        ans = max(ans, ed - st)  
        res = max(res, p[0] - ed)  
        st, ed = p[0], p[1]  
    else:  
        ed = max(ed, p[1])  
ans = max(ans, ed - st)  
print(ans, res)

真题演练

第十四届蓝桥杯省赛Python B 组 D 题


二分答案 + 区间合并


AC_code:

python 复制代码
import sys  
input = sys.stdin.readline  
inf = float('inf')  
  
n, length = map(int, input().split())  
grid = [list(map(int, input().split())) for _ in range(n)]  
  
def check(mid):  
    a = []  
    for pos, t in grid:  
        if t > mid:  
            continue  
        l = max(1, pos - (mid - t))  
        r = min(length, pos + (mid - t))  
        a.append((l, r))  
    a.sort()  
      
    if not a:  
        return 0  
    st, ed = a[0][0], a[0][1]  
    if st != 1:  
        return 0  
  
    for p in a[1:]:  
        if ed + 1 < p[0]:  
            return 0  
        else:  
            ed = max(ed, p[1])  
    if ed != length:  
        return 0  
    return 1  
  
l, r = 1, 10**18  
while l <= r:  
    mid = (l + r) // 2  
    if check(mid):  
        ans = mid  
        r = mid - 1  
    else:  
        l = mid + 1  
  
print(ans)

END
如果有更多问题或需要进一步的帮助,可以在评论区留言讨论哦!
如果喜欢的话,请给博主点个关注 谢谢

相关推荐
用户8356290780513 小时前
无需 Office:Python 批量转换 PPT 为图片
后端·python
爱理财的程序媛5 小时前
openclaw 盯盘实践
算法
markfeng85 小时前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi6 小时前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee6 小时前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay6 小时前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤6 小时前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean7 小时前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽8 小时前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi