最短路算法回顾1:Dijkstra(python)

题目是acwing 4871. 最早时刻

首先看数据范围,知时间复杂度最高也不过(nlogn)
看见题目第一行,突然惊觉,如果考试中没说(不含重边和自环),那么数据需要预处理,比如说,如果有两条边从a到b,根据题目要花费最少时间,肯定是保留a到b那条时间少的边。
题目要求计算从1号到n号的最短距离,脑海中就两个(Dijkstra和bellman),当有自环和负权重的图时,使用bellman,其他就Dj吧。
那么主体算法就是Dj为主,题目中说有禁止离开时刻表,又是升序,那么妥妥二分法。
from collections import defaultdict
import heapq as pq

def addtime(site, time):
    ls = no[site]
    if k[site] == 0 or ls[0] > time or ls[-1] < time:
        return time
    l, r = 0, len(ls)-1
    while l < r:
        mid = l + r >> 1
        if ls[mid] < time:
            l = mid + 1
        else:
            r = mid
    if ls[l] > time:
        return time
    while l < len(ls) and ls[l] == time:
        time += 1
        l += 1
    return time


n, m = map(int,input().split())
edge = defaultdict(dict)
k = [0]*(n+1)
no = [ [] ]
for _ in range(m):
    a, b, c = map(int,input().split())
    edge[a][b] = c
    edge[b][a] = c
for idx in range(1, n+1):
    ls = list(map(int,input().split()))
    k[idx] = ls[0]
    no.append(ls[1:])
qu = []
pq.heapify(qu)
pq.heappush(qu, (1, 0))
v = [float('inf')]*(n+1)
while qu:
    site, time = pq.heappop(qu)
    if time > v[site]: continue
    v[site] = time
    time_ = addtime(site, time)
    for nex in edge[site]:
        if edge[site][nex] + time_ < v[nex]:
            pq.heappush(qu, (nex, edge[site][nex] + time_))

if v[-1] == float('inf'):
    print(-1)
else:
    print(v[-1])
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值