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

相关推荐
ak啊14 分钟前
空间优化 Morris 遍历算法
算法
小羊在奋斗21 分钟前
【算法】数组、链表、栈、队列、树
数据结构·算法
KyollBM28 分钟前
数学——A. K-divisible Sum + D. Exam in MAC
c++·算法·macos
prettyxian33 分钟前
【c++】继承
开发语言·c++·算法
旧厂街小江37 分钟前
LeetCode第76题:最小覆盖子串
后端·算法·程序员
愚戏师40 分钟前
Python:函数式编程
开发语言·python·算法
iku!!1 小时前
【Python+HTTP接口】POST请求不同请求头构造
python·http
DogDaoDao1 小时前
Conda 虚拟环境创建:加不加 Python 版本的深度剖析
开发语言·人工智能·pytorch·python·深度学习·conda
Leo来编程1 小时前
Python学习第十九天
python·学习
如果是君1 小时前
Ubuntu20.04安装运行DynaSLAM
linux·python·深度学习·神经网络·ubuntu