【算法】 区间合并(附蓝桥杯真题) 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
如果有更多问题或需要进一步的帮助,可以在评论区留言讨论哦!
如果喜欢的话,请给博主点个关注 谢谢

相关推荐
Wonderful U4 分钟前
Python+Django实战|美食菜谱分享与食材采购一体化系统:食谱发布收藏、图文教程、食材商城、购物车、订单管理、美食点评、智能食谱推荐
python·django·美食
下午写HelloWorld7 分钟前
【概念与应用】轻量级加密算法LEA、动态脱敏算法DDA、零知识证明ZKP和优化协同交互协议OCIP
算法·区块链·密码学·安全架构·零知识证明
秦jh_15 分钟前
【LangChain核心组件】少样本提示(示例选择器)
人工智能·python·langchain
资深流水灯工程师22 分钟前
PyCharm 增强插件完整安装与配置指南(PySide6 开发专用)
ide·python·pycharm
飞舞哲27 分钟前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
Kobebryant-Manba30 分钟前
学习模型构造
python·深度学习·学习
天天进步201531 分钟前
Python全栈项目--基于Python的数据库管理工具
开发语言·数据库·python
阿提说说32 分钟前
我的 NVIDIA 考试攻略
python·大模型·agent
Coder-magician34 分钟前
《代码随想录》刷题打卡day12:二叉树part02
数据结构·c++·算法
xyz_CDragon43 分钟前
OpenClaw 局域网调用 Ollama 本地大模型:完整配置与踩坑指南
python·ai编程·集成学习·ollama·deepseek·openclaw