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

发布于:2024-05-10 ⋅ 阅读:(29) ⋅ 点赞:(0)

关键字:贪心

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

第一版👇

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。

第二版👇

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,做完这些发现保存已访问过位置也是多余的。。

最终版👇

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)


网站公告

今日签到

点亮在社区的每一天
去签到