蓝桥杯 算法提高 ADV-1169 区间覆盖问题 python AC

关键字:贪心

先对输入内容处理,只保存每个起点最长的那个终点,一步步替换当前位置为最长的那个终点,考虑到可能会有重叠(如1-4, 3-5),当找不到当前终点时,把当前位置-1继续找终点

第一版👇

python 复制代码
n, m = map(int, input().split())
d = {}
for _ in range(m):
    a, b = map(int, input().split())
    if a != b:
        if a not in d:
            d[a] = b
        elif a in d and d[a] < b:
            d[a] = b
now = 1
step = 0
vis = []
while now != n:
    if now in vis:
        step = -1
        break
    step += 1
    vis.append(now)
    while now not in d:
        now -= 1
        vis.append(now)
    now = d[now]
print(step)

有答案错误,看了测试点和关键字发现问题了,但是给了好多分。。

贪心做法:从起点开始保存每一步能够到达的最远位置,然后遍历起点到最远位置(即遍历上一步能够到达的所有位置),如果下一步能够到达更远的位置,更新最远位置。如果能够到达的最远位置小于当前位置(后来发现是多余的,因为无法小于)时跳出并返回-1。提交发现死循环:当能够到达的最远位置和当前位置重叠时无法结束(如只给1-4但要到5就会在4一直循环)。加入一个列表保存所有当前到达的位置,如果能够到达的最远位置已访问过也跳出并返回-1。

第二版👇

python 复制代码
n, m = map(int, input().split())
d = {}
for _ in range(m):
    a, b = map(int, input().split())
    if a != b:
        if a not in d:
            d[a] = b
        elif a in d and d[a] < b:
            d[a] = b
now, next, step, max_ind = 1, 0, 0, 1
vis = []
while max_ind < n:
    if max_ind < now or max_ind in vis:
        step = -1
        break
    vis.append(now)
    step += 1
    next = max_ind
    for i in range(now, max_ind + 1):
        if i in d and d[i] > max_ind:
            max_ind = d[i]
    now = next
print(step)

过了,但是代码看着自己都难受,很冗余的感觉。。

优化一下,优化过程中发现当前无法比能到达的最远距离更小,所以只要判断二者不相等就可以了,但是初始时它们都为1怎么办。。欸发现好像初始时当前位置不太重要,只用来为遍历时提供范围就行了,于是把当前位置设为0,能够达到的最远距离设为1,做完这些发现保存已访问过位置也是多余的。。

最终版👇

python 复制代码
n, m = map(int, input().split())
d = {}
for _ in range(m):
    a, b = map(int, input().split())
    if a != b:
        if a not in d:
            d[a] = b
        elif a in d and d[a] < b:
            d[a] = b
now, next, max_ind, step = 0, 1, 1, 0
while max_ind < n:
    if max_ind == now:
        step = -1
        break
    step += 1
    next = max_ind
    for i in range(now, next + 1):
        if i in d and d[i] > max_ind:
            max_ind = d[i]
    now = next
print(step)
相关推荐
qq_158895411114 小时前
AI 音乐生成完成后,音频 URL 为什么会过期?一套可恢复的交付方案
python·api·ai音乐
Warson_L6 小时前
高性能架构设计
python·go
databook7 小时前
新数据到手,先跑哪几步检查
python·数据分析
GoAI7 小时前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试
czq_26867194877 小时前
Python打卡第46天
开发语言·python
Pniubi7 小时前
力扣54.螺旋矩阵
算法·leetcode·矩阵
Flynt8 小时前
日涨4000星的OSINT工具,我拿Linus的用户名和一个随机字符串实测了一遍
python·安全
choumou_M10 小时前
算法_1:由浅入深学习快速排序QuickSort
学习·算法·排序算法
Coder_Shenshen10 小时前
罗克韦尔ACD工程归档离线变量树解析
算法·c#