PROB1009 单源最短路
描述:
给一个n(1≤n≤2500)个点m(1≤m≤6200)条边的无向图,求s到t的最短路。
输入:
第一行四个由空格隔开的整数n、m、s、t。
之后的m行,每行三个正整数si、ti、wi(1≤wi≤10^9),表示一条从si到ti长度为wi的边。
输出:
一个整数表示从s到t的最短路长度。数据保证至少存在一条道路。
样例输入:
7 11 5 4 2 4 2 1 4 3 7 2 2 3 4 3 5 7 5 7 3 3 6 1 1 6 3 4 2 4 3 5 6 3 7 2 1
样例输出:
7
基于python实现的代码:
import heapq
def dijkstra(n,edges,s):
dist = {node:float('inf') for node in range(1,n+1)}
dist[s] = 0
pq = [(0,s)]
while pq:
current_dist, current_node = heapq.heappop(pq)
if current_dist > dist[current_node]:
continue
for to_node, weight in edges[current_node]:
new_dist = current_dist + weight
if new_dist < dist[to_node]:
dist[to_node] = new_d