Skip to content

Instantly share code, notes, and snippets.

@nyanshell
Created March 23, 2014 14:08
Show Gist options
  • Save nyanshell/9723523 to your computer and use it in GitHub Desktop.
Save nyanshell/9723523 to your computer and use it in GitHub Desktop.
simple topological sort
#!/usr/bin/python3
"""
TIMUS 1022
ACCEPTED
2014-03-23
"""
q = set()
n = int(input())
ch = [[] for i in range(0, n)]
pa = [0 for i in range(0, n)]
ans = []
for i in range(0, n):
tc = [int(x) for x in input().split(' ')]
for t in tc:
if t:
ch[ i ].append(t - 1)
pa[ t - 1 ] += 1
for i in range(0, n):
if pa[ i ]:
q.add(i)
while len(ans) != n:
t = q.pop()
ans.append(t)
for c in ch[t]:
pa[c] -= 1
if pa[c] and c not in ans:
q.add(c)
print (" ".join([str(a + 1) for a in ans]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment