Created
March 23, 2014 14:08
-
-
Save nyanshell/9723523 to your computer and use it in GitHub Desktop.
simple topological sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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