from typing import AbstractSet, List, Sequence
def topological_sort(graph: Sequence[AbstractSet[int]]) -> List[int]:
"""Returns a list of nodes in topologically sorted order."""
indegrees = [0] * len(graph)
for successors in graph:
for v in successors:
indegrees[v] += 1
stack = [u for u, indegree in enumerate(indegrees) if indegree == 0]
result = []
while stack:
u = stack.pop()
result.append(u)
for v in graph[u]:
indegrees[v] -= 1
if indegrees[v] == 0:
stack.append(v)
if len(result) != len(graph):
raise ValueError('found a cycle')
return result
# graph = ...
ts = graphlib.TopologicalSorter(graph)
answer = []
heap = []
ts.prepare()
while ts:
for node in ts.get_ready():
heapq.heappush(heap, node)
cur_node = heapq.heappop(heap)
answer.append(cur_node)
ts.done(cur_node)
return answer