#!/usr/bin/env python3
from topsort import topsort
from math import inf
def shortest(root,G):
n = len(G);
dist = [inf] * n
dist[root] = 0
(rank,order) = topsort(G)
In = inbound(G)
for j in range(rank[root]+1,n):
v = order[j]
for (prev,w) in In[v]:
if w+dist[prev] < dist[v]:
dist[v]=w+dist[prev]
return dist
def inbound(G):
n = len(G)
In = [ [] for j in range(n) ]
for v in range(n):
for (u,w) in G[v]:
In[u].append((v,w))
return In
if __name__ == "__main__":
# [(dest,weight),...] # from
Graph = [ [(2,4),(3,4),(5,3)],
[(0,4),(2,1),(3,3)],
[(3,2),(4,4)],
[(4,6)],
[],
[(4,5)] ]
d = shortest(0,Graph)
print(d)