Skip to content

Instantly share code, notes, and snippets.

@caseploeg
Created March 1, 2024 22:30
Show Gist options
  • Save caseploeg/381b770639119ca5c9eb28129a3218ec to your computer and use it in GitHub Desktop.
Save caseploeg/381b770639119ca5c9eb28129a3218ec to your computer and use it in GitHub Desktop.
import sys
import heapq
from collections import defaultdict
v,e = sys.stdin.readline().strip().split()
adj = defaultdict(list)
d = dict()
for _ in range(int(e)):
u, v, w = sys.stdin.readline().strip().split()
adj[u].append((v, int(w)))
adj[v].append((u, int(w)))
d[u] = float('inf')
d[v] = float('inf')
s = sys.stdin.readline().strip()
d[s] = 0
def dijkstra(adj, d, s):
q = [(d[s],s)]
while q:
pathlen, cur = heapq.heappop(q)
for v,w in adj[cur]:
if pathlen + w < d[v]:
d[v] = pathlen + w
heapq.heappush(q,(d[v],v))
dijkstra(adj,d, s)
print(d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment