dijkstra(堆优化)
卡码网 47. 参加科学大会
代码随想录
import heapq
V, E = map(int, input().split())
graph = {}
for _ in range(E):
s,t,val = map(int, input().split())
if s not in graph:
graph[s] = []
graph[s].append((t,val))
visited = [False] * (V+1)
distance_queue = []
heapq.heappush(distance_queue, (0,1))
distance = [float("+inf")] * (V + 1)
while distance_queue:
v, s = heapq.heappop(distance_queue)
if visited[s]:
continue
visited[s] = True
neighbor_nodes = graph.get(s,None)
if not neighbor_nodes:
continue
for neighbor_u, neighbor_v in neighbor_nodes:
if not visited[neighbor_u]:
new_dist = v + neighbor_v
if new_dist < distance[neighbor_u]:
distance[neighbor_u] = new_dist
heapq.heappush(distance_queue, (new_dist, neighbor_u))
print(distance[-1]) if distance[-1] != float("+inf") else print(-1)
Bellman_ford 算法
卡码网 94. 城市间货物运输 I
代码随想录
V, E = map(int, input().split())
graph = []
for i in range(E):
s,t,v = map(int, input().split())
graph.append((s,t,v))
distance = [float("+inf")] * (V+1)
distance[1] = 0
for i in range(1, V):
updated = False
for s,t,v in graph:
if distance[s] != float("+inf") and distance[s] + v < distance[t]:
distance[t] = distance[s] + v
updated = True
if not updated:
break
print(distance[-1]) if distance[-1] != float("+inf") else print("unconnected")