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

相关推荐
用户8356290780511 小时前
使用 Python 在 Excel 中添加和自定义迷你图
后端·python
老师我太想进步了20261 小时前
【数据结构-4】算法美学之顺序表
数据结构·算法
用户8356290780511 小时前
使用 Python 在 Excel 图表中添加趋势线与回归方程
后端·python
风影同志783241 小时前
编码器是激活函数吗?—— 一个看起来很像、其实不是的类比
算法
特立独行的猫A1 小时前
一份 Markdown 发十个平台:cspub 一稿多投
java·后端·python
UIU1141 小时前
P1481 魔族密码
c++·算法·动态规划
深蓝AI2 小时前
HTTPX 超时 1 秒,接口为何还能跑 2.4 秒?
python
CyrusYiVPP2 小时前
哪个用户会再来买?RFM模型+plotly画出用户分层,数据分析实战第2期
人工智能·python
李帅5153 小时前
用 CPU 做发票识别:从 OCR 文本行到结构化明细表的 4 个硬骨头
python