Skip to content

Instantly share code, notes, and snippets.

@yurahuna
Created April 6, 2017 06:56
Show Gist options
  • Save yurahuna/f9628359776af230f0a48d21929eb01e to your computer and use it in GitHub Desktop.
Save yurahuna/f9628359776af230f0a48d21929eb01e to your computer and use it in GitHub Desktop.
import heapq
def dijkstra(G, s):
n = len(G)
INF = float("inf")
d = [INF] * n
d[s] = 0
pq = []
heapq.heappush(pq, (0, s)) # (cost, vertex)
while pq:
c, v = heapq.heappop(pq)
if d[v] < c:
continue
for nv, nc in G[v]:
if d[nv] > d[v] + nc:
d[nv] = d[v] + nc
heapq.heappush(pq, (d[nv], nv))
return d
n = input()
G = [[] for i in xrange(n)]
for i in xrange(n):
li = map(int, raw_input().split())
for j in xrange(li[1]):
G[i].append((li[2 * (j + 1)], li[2 * (j + 1) + 1]))
d = dijkstra(G, 0)
for i, c in enumerate(d):
print i, c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment