题解 | 【模板】单源最短路2

【模板】单源最短路2

https://www.nowcoder.com/practice/7c1740c3d4ba4b3486df4847ee6e8fc7

from collections import defaultdict
import sys
import heapq
input=sys.stdin.readline
n,m = map(int, input().split())
neighbors = defaultdict(list)
for _ in range(m):
    u,v,w = map(int, input().split())
    neighbors[u].append((v,w))
    neighbors[v].append((u,w))

pq = []
heapq.heappush(pq,(0,1)) #tuple[0]是优先级,在这里用距离表示,tuple[1]是顶点编号。
visited = [0]*5001
while len(pq):
    cur_d, cur_v = heapq.heappop(pq) # 优先队列弹出距离最小的那个
    visited[cur_v] = 1 # 标记访问过
    if cur_v == n: 
        print(cur_d)
        break
    for v, w in neighbors[cur_v]:# 访问当前cur_v 的近邻和权值
        if visited[v] == 0:
            heapq.heappush(pq, (cur_d+w, v)) #自动排序
else:
    print(-1)

全部评论

相关推荐

嘀哩咕噜说啥呢:27届,这简历,强的逆天,大厂实习随便冲,面经多少看点,hot100刷完,大厂随便挑了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务