Skip to content

Instantly share code, notes, and snippets.

@kjsman
Created September 14, 2021 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjsman/2a9650bc9ee0a7eb08c456e171b0bae0 to your computer and use it in GitHub Desktop.
Save kjsman/2a9650bc9ee0a7eb08c456e171b0bae0 to your computer and use it in GitHub Desktop.
n, m = map(int, input().split())
g = {i: [] for i in range(n)}
for _ in range(m):
a, b, c = map(int, input().split())
g[a - 1].append([b - 1, c])
ds = [0] + [float('inf')] * (n - 1)
def cycle():
ran = False
for a in g:
for b, c in g[a]:
if ds[b] > ds[a] + c:
ran = True
ds[b] = ds[a] + c
return ran
for _ in range(n):
cycle()
if cycle():
print(-1)
exit()
for d in ds[1:]:
print(d if d < float('inf') else -1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment