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

相关推荐
江沉晚呤时4 小时前
在 C# 中调用 Python 脚本:实现跨语言功能集成
python·microsoft·c#·.net·.netcore·.net core
今天背单词了吗9804 小时前
算法学习笔记:19.牛顿迭代法——从原理到实战,涵盖 LeetCode 与考研 408 例题
笔记·学习·算法·牛顿迭代法
电脑能手4 小时前
如何远程访问在WSL运行的Jupyter Notebook
ide·python·jupyter
Edward-tan5 小时前
CCPD 车牌数据集提取标注,并转为标准 YOLO 格式
python
老胖闲聊5 小时前
Python I/O 库【输入输出】全面详解
开发语言·python
jdlxx_dongfangxing5 小时前
进制转换算法详解及应用
算法
倔强青铜三5 小时前
苦练Python第18天:Python异常处理锦囊
人工智能·python·面试
倔强青铜三6 小时前
苦练Python第17天:你必须掌握的Python内置函数
人工智能·python·面试
迷路爸爸1806 小时前
让 VSCode 调试器像 PyCharm 一样显示 Tensor Shape、变量形状、变量长度、维度信息
ide·vscode·python·pycharm·debug·调试
why技术6 小时前
也是出息了,业务代码里面也用上算法了。
java·后端·算法