Problem:
Topological Sort   A directed acyclic graph (DAG) can be used to represent the ordering of tasks. Tasks are represented by vertices and constraints where one task can begin before another, are represented by edges. For example, in the above example, you can undertake task B after both task A and task B are finished. You can obtain the proper sequence of all the tasks by a topological sort. Given a DAG $G$, print the order of vertices after the topological sort. Input A directed graph $G$ is given in the following format: $|V|\;|E|$ $s_0 \; t_0$ $s_1 \; t_1$ : $s_{|E|-1} \; t_{|E|-1}$   $|V|$ is the number of vertices and $|E|$ is the number of edges in the graph. The graph vertices are named with the numbers $0, 1,..., |V|-1$ respectively. $s_i$ and $t_i$ represent source and target nodes of $i$-th edge (directed). Output Print the vertices numbers in order. Print a number in a line. If there are multiple possible solutions, print any one of them (the solution is judged by a special validator). Constraints  $1 \leq |V| \leq 10,000$  $0 \leq |E| \leq 100,000$  There are no parallel edges in $G$  There are no self loops in $G$  Sample Input 6 6
0 1
1 2
3 1
3 4
4 5
5 2 Sample Output 0
3
1
4
5
2

Solution (Python):
def topological_sort(G):
  d = {}
  nodes = set()
  for i in G:
    if i not in d:
      d[i] = set()
    for j in G[i]:
      if j not in d:
        d[j] = set()
      d[j].add(i)
  for i in d:
    if len(d[i]) == 0:
      nodes.add(i)
  visited = set()
  ret = []
  while len(visited) < len(G):
    n = nodes.pop()
    if n not in visited:
      for j in G[n]:
        d[j].discard(n)
        if len(d[j]) == 0 and j not in visited:
          nodes.add(j)
      ret.append(n)
      visited.add(n)
  return ret




n,m = list(map(int, input().split(' ')))
G = {}
for i in range(n):
  G[i] = set()
for _ in range(m):
  s,t = list(map(int, input().split(' ')))
  G[s].add(t)

L = topological_sort(G)

for n in L:
  print(n)

Solution (Python):

"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_4_B&lang=jp

"""
import sys
from collections import deque


def bfs(u, result, out_edge, in_degree, processed):
    q = deque()
    q.append(u)
    processed[u] = True
    while q:
        u = q.popleft()
        result.append(u)
        for e in out_edge[u]:
            in_degree[e] -= 1
            if in_degree[e] == 0 and processed[e] == False:
                processed[e] = True
                q.append(e)





def solve(V, in_degree, out_edge):
    result = []
    processed = [False for _ in range(V)]

    for i, u in enumerate(in_degree):
        if u == 0 and processed[i] == False:
            bfs(i, result, out_edge, in_degree, processed)
    return result


def main(args):
    V, E = [int(x) for x in input().split(' ')]
    in_degree = [0 for _ in range(V)]
    out_edge = [[] for _ in range(V)]
    for _ in range(E):
        s, t = [int(x) for x in input().split(' ')]
        out_edge[s].append(t)
        in_degree[t] += 1

    result = solve(V, in_degree, out_edge)
    print('\n'.join(map(str, result)))


if __name__ == '__main__':
    main(sys.argv[1:])

Solution (Python):
from collections import defaultdict


def dfs(u, used, edges, result):
    used[u] = True
    for v in edges[u]:
        if not used[v]:
            dfs(v, used, edges, result)
    result.append(u)


def main():
    N, M = map(int, input().split())

    used = [False] * N
    edges = defaultdict(list)
    for _ in range(M):
        s, t = map(int, input().split())
        edges[s].append(t)

    result = []
    for i in range(N):
        if not used[i]:
            dfs(i, used, edges, result)

    print(*result[::-1])


if __name__ == '__main__':
    main()

Solution (Python):
from collections import defaultdict


def topological_sort(N, edges):
    def dfs(u):
        used[u] = True
        for v in edges[u]:
            if not used[v]:
                dfs(v)
        result.append(u)

    used = [False] * N
    result = []
    for i in range(N):
        if not used[i]:
            dfs(i)

    return result[::-1]


def main():
    N, M = map(int, input().split())
    edges = defaultdict(list)
    for _ in range(M):
        s, t = map(int, input().split())
        edges[s].append(t)

    ans = topological_sort(N, edges)
    print(*ans)


if __name__ == '__main__':
    main()

Solution (Python):

from collections import deque

def inpl(): return tuple(map(int, input().split()))

V, E = inpl()
indeg = [0] * V
adj = {k: [] for k in range(V)}

for _ in range(E):
    s, t = inpl()
    adj[s].append(t)
    indeg[t] += 1

Q = deque([i for i, ind in enumerate(indeg) if ind == 0])
res = []

while Q:
    q = Q.popleft()
    for i in adj[q]:
        indeg[i] -= 1
        if indeg[i] == 0:
            Q.append(i)
    res.append(q)

for r in res:
    print(r)

Solution (Python):
from collections import defaultdict, deque

V, E = map(int, input().split())
G = defaultdict(list)

for i in range(E):
    s, t = map(int, input().split())
    G[s].append(t)

ans = deque([])
visited = defaultdict(bool)
def visit(v):
    if visited[v]: return
    visited[v] = True
    for k in G[v]:
        visit(k)
    ans.appendleft(v)

for v in range(V):
    visit(v)

print('\n'.join(map(str, ans)))

Solution (Python):
from collections import defaultdict
vertice, edge = (int(n) for n in input().split(" "))
connect = defaultdict(list)
indegree = [0 for n in range(vertice)]
for _ in range(edge):
    s, t = (int(n) for n in input().split(" "))
    connect[s].append(t)
    indegree[t] += 1
answer = []
zeroin = []
for i, n in enumerate(indegree):
    if n == 0:
        zeroin.append(i)
while len(zeroin) > 0:
    next_v = zeroin.pop()
    indegree[next_v] -= 1
    answer.append(next_v)
    for c in connect[next_v]:
        indegree[c] -= 1
        if indegree[c] == 0:
            zeroin.append(c)
for a in answer:
    print(a)

Solution (Python):
from collections import defaultdict
import sys
re = sys.stdin
vertice, edge = (int(n) for n in re.readline().split(" "))
connect = defaultdict(list)
indegree = [0 for n in range(vertice)]
for _ in range(edge):
    s, t = (int(n) for n in re.readline().split(" "))
    connect[s].append(t)
    indegree[t] += 1
answer = []
zeroin = []
for i, n in enumerate(indegree):
    if n == 0:
        zeroin.append(i)
while len(zeroin) > 0:
    next_v = zeroin.pop()
    indegree[next_v] -= 1
    answer.append(next_v)
    for c in connect[next_v]:
        indegree[c] -= 1
        if indegree[c] == 0:
            zeroin.append(c)
for a in answer:
    print(a)

Solution (Python):


from collections import deque


if __name__ == '__main__':

    n, m = [int(s) for s in input().split()]
    E = [set() for _ in range(n)]
    for _ in range(m):
        s, t = [int(s) for s in input().split(" ")]
        E[s].add(t)

    color = [0] * n
    indeg = [0] * n
    for s in range(n):
        for t in E[s]:
            indeg[t] += 1

    Q = deque()
    out = []

    def bfs(s):
        Q.append(s)
        color[s] = 1
        while Q:
            u = Q.popleft()
            out.append(u)
            for v in E[u]:
                indeg[v] -= 1
                if indeg[v] == 0 and color[v] == 0:
                    color[v] = 1
                    Q.append(v)

    for u in range(n):
        if indeg[u] == 0 and color[u] == 0:
            bfs(u)

    print("\n".join(map(str, out)))

Solution (Python):
V, E = map(int,input().split())

L = []
visited = [0 for i in range(V)]
edges = [[] for i in range(V)]
flag = 0

def visit(x):
  if visited[x] == 1:
    flag = 1
  elif not visited[x]:
    visited[x] = 1
    for e in edges[x]:
      visit(e)
    visited[x] = 2
    L.insert(0,x)

for i in range(E):
  s, t = map(int,input().split())
  edges[s].append(t)

for i in range(V):
  if not visited[i]:
    visit(i)

for i in L:
  print(i)

Solution (Python):
N, M = map(int, input().split())
G = [[] for i in range(N)]
for i in range(M):
    s, t = map(int, input().split())
    G[s].append(t)

ans = []
V = set()

def dfs(n):
    for e in G[n]:
        if e not in V:
            dfs(e)
    if n not in V:
        ans.append(n)
        V.add(n)


for i in range(N):
    if i not in V:
        if i not in V:
            dfs(i)
            print()

print(*ans[::-1], sep="\n")

Solution (Python):
N, M = map(int, input().split())
G = [[] for i in range(N)]
for i in range(M):
    s, t = map(int, input().split())
    G[s].append(t)

ans = []
V = set()

def dfs(n):
    for e in G[n]:
        if e not in V:
            dfs(e)
    ans.append(n)
    V.add(n)


for i in range(N):
    if i not in V:
        if i not in V:
            dfs(i)
            print()

print(*ans[::-1], sep="\n")

Solution (Python):
N, M = map(int, input().split())
G = [[] for i in range(N)]
for i in range(M):
    s, t = map(int, input().split())
    G[s].append(t)


def topological_sort(g):
    topological_list = []
    visited = set()

    def dfs(n):
        for e in g[n]:
            if e not in visited:
                dfs(e)
        topological_list.append(n)
        visited.add(n)

    for i in range(len(g)):
        if i not in visited:
            dfs(i)

    return topological_list[::-1]


print(*topological_sort(G), sep="\n")

Solution (Python):
from collections import deque


def topological(N, LIST):  
    incnt = [0] * N
    CHILD = [set() for _ in range(N)]
    for a, b in LIST:
        CHILD[a].add(b)
        incnt[b] += 1

    TPLGSORT = []
    que = deque([i for i, num in enumerate(incnt) if num == 0])
    while len(que) > 0:
        q = que.popleft()
        for i in CHILD[q]:
            incnt[i] -= 1
            if incnt[i] == 0:
                que.append(i)
        TPLGSORT.append(q)
    return TPLGSORT


n, m = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(m)]

tplg = topological(n, ab)
print(*tplg, sep='\n')

Solution (Python):
from collections import deque

def sts():
    for i in g:
        for j in i:
            incnt[j]+=1 
    for i in range(v):
        if incnt[i]==0:
            q.append(i)
    
    while q:
        e=q.popleft()
        ans.append(e)
        for i in g[e]:
            incnt[i]-=1
            if incnt[i]==0:
                q.append(i)
    for i in ans:
        print(i)
            
v,e=map(int,input().split())
g=[[] for i in range(v)]

incnt=[0]*v

q=deque()

ans=[]
for i in range(e):
    x,y=map(int,input().split())
    g[x].append(y)
sts()

Solution (Python):
from collections import deque

v, e = map(int, input().split())
adj = [[] for _ in range( v)]
inflow = [0] * v
for _ in range(e):
    s, t = map(int, input().split())
    inflow[t] += 1
    adj[s].append(t)

def topological_sort(adj, inflow):
    is_visited = [False] * len(inflow)
    res = []

    def bfs(s):
        
        q = deque([s])
        is_visited[s] = True
        res.append(s)
        while q:
            p = q.popleft()
          
            for r in adj[p]:
                inflow[r] -= 1
                if (inflow[r] == 0) and (not is_visited[r]):
                    q.append(r)
                    is_visited[r] = True
                    res.append(r)

    for x in range(len(inflow)):
        if (inflow[x] == 0) and (not is_visited[x]):
            bfs(x)
    return res

for i in topological_sort(adj, inflow):
    print(i)

Solution (Python):
def main():
    N, M = (int(i) for i in input().split())
    G = [[] for _ in range(N)]
    deg = [0]*N
    for _ in range(M):
        a, b = (int(i) for i in input().split())
        G[a].append(b)
        deg[b] += 1

    from collections import deque

    def topological_sort():
        que = deque()
        ans = []*N
        for i in range(N):
            if deg[i] == 0:
                que.append(i)
                ans.append(i)

        while que:
            u = que.popleft()
            for v in G[u]:
                deg[v] -= 1
                if deg[v] == 0:
                    que.append(v)
                    ans.append(v)
        return ans

    print(*topological_sort(), sep="\n")


if __name__ == '__main__':
    main()

Solution (Python):
from sys import stdin
input = stdin.readline

from collections import deque, defaultdict

def bfs(s):
    Q.append(s)
    color[s] = 1

    while Q:
        u = Q.popleft()

        out.append(u)

        for edge in range(e):
            s, t = list(map(int, lines[edge+1].split()))
            if s == u:
                indeg[t] -= 1
                if indeg[t] == 0 and color ==0:
                    color[t] = 1
                    Q.append(t)


lines = stdin.readlines()

v, e = list(map(int, lines[0].split()))

out = []
outs = defaultdict(list)


color = [0] * v
indeg = [0] * v

for i in range(e):
    s, t = list(map(int, lines[i+1].split()))
    outs[s].append(t)
    indeg[t] += 1

Q = deque(v1 for v1 in range(v) if indeg[v1] == 0)

while Q:
    v1 = Q.popleft()
    out.append(v1)

    for v2 in outs[v1]:
        indeg[v2] -= 1
        if indeg[v2] == 0:
            Q.append(v2)

for i in out:
    print(i)

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 

from decimal import *



V, E = MAP()
st = [LIST() for _ in range(E)]

graph = [[] for _ in range(V)]
dag = [0]*V
for s, t in st:
	graph[s].append(t)
	dag[t] += 1

ans = [i for i, x in enumerate(dag) if x == 0]
q = deque([i for i, x in enumerate(dag) if x == 0])
while q:
	S = q.popleft()
	for node in graph[S]:
		dag[node] -= 1
		if dag[node] == 0:
			ans.append(node)
			q.append(node)

if sum(dag):
	print(-1)
else:
	print(*ans, sep="\n")

Solution (Python):
import sys
from collections import deque

sys.setrecursionlimit(10**7)

V, E = map(int, input().split())
G = [[] for _ in range(V)]

for _ in range(E):
    s, t = map(int, input().split())
    G[s].append(t)

visited = [0]*V
ans = deque([])

def dfs(u):
    visited[u] = 1
    for i in G[u]:
        if visited[i] == 0:
                dfs(i)
    ans.appendleft(u)

for s in range(V):
    if visited[s] == 0:
        dfs(s)

for a in ans:
    print(a)

Solution (Python):
import queue

def bfs(u):
    q = queue.Queue()
    q.put(u)
    
    while not q.empty():
        v = q.get()
        color[v] = 'black'
        ans.append(v)
        for w in Adj[v]:
            indeg[w] -= 1
            if indeg[w] == 0 and color[w] == 'white':
                q.put(w)
                
    return
        

n,m = map(int,input().split())
color = ['white' for _ in range(n)]
Adj = [[] for _ in range(n)]
indeg = [0]*n
ans = []
for i in range(m):
    s,t = map(int,input().split())
    Adj[s].append(t)
    indeg[t] += 1
    
for i in range(n):
    if indeg[i] == 0 and color[i] == 'white':
        bfs(i)
        
for i in range(n):
    print(ans[i])

Solution (Python):
from collections import deque
from typing import List, Optional


def topological_sort(
    graph: List[List[int]], in_degrees: List[int], first_index: int = 0
) -> Optional[List[int]]:
    """Topological sort that uses Kahn's algorithm and is able to detect cycles.
    Returns:
        If the given graph is DAG, a list of sorted vertices is returned.
        Otherwise, if loops are detected, None is returned.
    """
    V = len(graph) + first_index
    order = [i for i in range(first_index, V) if not in_degrees[i]]
    queue = deque(order)

    while queue:
        u = queue.popleft()
        for v in graph[u]:
            in_degrees[v] -= 1
            if not in_degrees[v]:
                queue.append(v), order.append(v)

    return order if len(order) + first_index == V else None


def grl_4_b():
    
    V, _, *ST = map(int, open(0).read().split())
    graph = [[] for _ in range(V)]
    in_degrees = [0] * V
    for s, t in zip(*[iter(ST)] * 2):
        graph[s].append(t)
        in_degrees[t] += 1

    res = topological_sort(graph, in_degrees)
    print("\n".join(map(str, res)))


if __name__ == "__main__":
    grl_4_b()

Solution (Python):
from collections import deque
def topological_sort(n,G):
    seq_sorted = []
    st = deque()

    ct_to_edges = [0]*n
    for edges in G:
        for node in edges:
            ct_to_edges[node]+=1
    
    for i,ct in enumerate(ct_to_edges):
        if ct==0:
            st.append(i)
    
    while st:
        node = st.pop()
        seq_sorted.append(node)
        for node in G[node]:
            ct_to_edges[node]-=1
            if ct_to_edges[node]==0:
                st.append(node)
    
    return seq_sorted
def main():
    n,m = map(int,input().split())
    G = [[] for _ in range(n)]
    for _ in range(m):
        s,t = map(int,input().split())
        G[s].append(t)

    topo_seq =  topological_sort(n,G)
    for i in topo_seq:
        print(i)
main()

Solution (Python):
v,e=map(int,input().split())
from collections import defaultdict
incnt=defaultdict(int)
edges=[[] for i in range(0+v)]
for i in range(e):
    """
    edges[_].append((__,___))
    incnt[__]+=1
    """
    _,__=map(int,input().split())
    edges[_].append(__)
    incnt[__]+=1
    """
"""
from collections import deque
dq=deque([])
topo=[]
for i in range(v):
    if incnt[i]==0:
        dq.append(i)
while dq:
    a=dq.popleft()
    for to in edges[a]:
        incnt[to]-=1
        if incnt[to]==0:dq.append(to)
    topo.append(a)
print(*topo,sep="\n")

Solution (Python):
from collections import deque
V,E = map(int,input().split())
G = [[] for _ in range(V)]
reached = [False]*V
indeg = [0]*V
for _ in range(E):
    s,t = map(int,input().split())
    G[s].append(t)
    indeg[t] += 1
out = []

def bfs(s):
    Q = deque()
    Q.append(s)
    reached[s] = True
    while Q:
        u = Q.popleft()
        out.append(u)
        for v in G[u]:
            indeg[v] -= 1
            if indeg[v] == 0 and reached[v] == False:
                reached[v] = True
                Q.append(v)

def topologicalSort():
    for u in range(V):
        if indeg[u] == 0 and reached[u] == False: bfs(u)

topologicalSort()
for i in out: print(i)

Solution (Python):
v, e = map(int, input().split())

adjacency_list = [[] for i in range(v)]

queue = []
deg = [0] * v

for _ in range(e):
    s, t = map(int, input().split())
    adjacency_list[s].append(t)
    deg[t] += 1
    
for i in range(v):
    if deg[i] == 0:
        queue.append(i)
        print(i)
        
while queue:
    vertex = queue.pop(0)
    for v in adjacency_list[vertex]:
        deg[v] -= 1
        if deg[v] == 0:
            queue.append(v)
            print(v)

Solution (Python):




from collections import deque

from collections import defaultdict
adj = defaultdict(lambda: [])


n_V, n_E = list(map(int, input().split()))
indeg = [0] * n_V  
for _ in range(n_E):
    s, t = list(map(int, input().split()))
    indeg[t] += 1  
    adj[s].append(t)



def topological_sort(dag, indeg):
    '''
    dag ... default dictで定義された隣接リスト(DAGを想定)
    indeg ... 各ノードについての流入量のリスト(inputのときについでにやったほうが計算量若干少なく済むでしょ？本質じゃないけど)
    '''
    is_visited = [False] * len(indeg)  
    ret = []  
    perm = [-1] * len(indeg)  

    que = deque()  
    for i, deg in enumerate(indeg):
        if deg == 0:
            que.append((i, 0))
            is_visited[i] = True

    while que:
        u, cnt = que.popleft()  
        ret.append(u)  
        perm[u] = cnt
        for to in dag[u]:  
            indeg[to] -= 1  
            if indeg[to] or is_visited[to]:
                continue  
            que.append((to, cnt + 1))  
            is_visited[to] = True

    if False in is_visited:
        print(is_visited)
        raise ValueError('inputted graph is not DAG')

    return ret, perm


ans, _ = topological_sort(adj, indeg)
print(*ans, sep='\n')

Solution (Python):


"""
Performs topological sorting of the given DAG using Kahn's algorithm.

Verification: []()
"""

import heapq


class TopologicalSortError(Exception):
    """This exception is raised when something gets wrong while performing `topological_sort`.
    """    
    pass


def topological_sort(num_vs, adj_vs):
    """Performs topological sorting of the given DAG.

    This function computes the lexicographically least
    topological order of the given DAG.

    Parameters:

    - `num_vs`: The number of vertices of the DAG.
    - `adj_vs` The adjacency list of the DAG.

    Returns: the lexicographically least topological order as a list.
    
    Raises `TopologicalSortError` if the given graph is not a DAG.
    """
    
    in_deg = [0 for _ in range(num_vs)]
    for dests in adj_vs:
        for dest in dests:
            in_deg[dest] += 1
    sorted_vs = []
    pq = []
    for s in range(num_vs):
        if in_deg[s] == 0:
            heapq.heappush(pq, s)
    while pq:
        u = heapq.heappop(pq)
        sorted_vs.append(u)
        for v in adj_vs[u]:
            in_deg[v] -= 1
            if in_deg[v] == 0:
                heapq.heappush(pq, v)
    if all(x == 0 for x in in_deg):
        return sorted_vs
    else:
        raise TopologicalSortError("The graph has a cycle")


def main():
    v, e = map(int, input().split())
    adj_vs = [set() for _ in range(v)]
    for _ in range(e):
        s, t = map(int, input().split())
        adj_vs[s].add(t)
    for u in topological_sort(v, adj_vs):
        print(u)


if __name__ == "__main__":
    main()

Solution (Python):
V,E = list(map(int,input().split()))


visit=[]
no_visit=list(range(V))


enter=[0]*V


ad_list=[[] for _ in range(V)]

for e in range(E):
    start,end=list(map(int,input().split()))
    ad_list[start].append(end)
    enter[end]+=1
    
enter , ad_list

while True:
    if len(visit)==V:
        break
        
    for n_v_idx,n_v in enumerate(no_visit):
        e=enter[n_v]
        if e == 0:
            v=no_visit.pop(n_v_idx)
            visit.append(v)
            for a in ad_list[n_v]:
                enter[a]=enter[a]-1
for v in visit:
    print(v)

Solution (Python):
from collections import deque

class Graph(): 
    def __init__(self, n, edge, indexed=1):
        self.n = n
        self.graph = [[] for _ in range(n)]
        self.rev = [[] for _ in range(n)]
        self.deg = [0 for _ in range(n)]
        for e in edge:
            self.graph[e[0] - indexed].append(e[1] - indexed)
            self.rev[e[1] - indexed].append(e[0] - indexed)
            self.deg[e[1] - indexed] += 1

    def topological_sort(self):
        deg = self.deg[:]
        res = [i for i in range(self.n) if deg[i] == 0]
        queue = deque(res)
        used = [False for _ in range(self.n)]
        while queue:
            node = queue.popleft()
            for adj in self.graph[node]:
                deg[adj] -= 1
                if deg[adj] == 0:
                    queue.append(adj)
                    res.append(adj)
        return res


import sys
input = sys.stdin.readline

N, M = map(int, input().split())
E = [tuple(map(int, input().split())) for _ in range(M)]

g = Graph(N, E, 0)
print('\n'.join(map(str, g.topological_sort())))

Solution (Python):
from collections import deque

V, E = map(int, input().split())


g = [[] for _ in range(V)]


in_E = [0 for _ in range(V)]

for _ in range(E):
    s, t = map(int, input().split())
    g[s].append(t)
    in_E[t] += 1



d = deque()

for i in range(V):
    if in_E[i] == 0:
        d.append(i)

ans = []

while d:
    
    v = d.popleft()
    
    
    for u in g[v]:
        
        in_E[u] -= 1
        if in_E[u] == 0:
            d.append(u)
    ans.append(v)

for i in ans:
    print(i)

Solution (Python):
from collections import deque
ans = deque()
V,E = map(int,input().split())
C = [[] for _ in range(V)]
for _ in range(E):
    tmp = list(map(int,input().split()))
    C[tmp[0]].append(tmp[1])

visited = [False]*V


def DFS(node):
    visited[node] = True
    for adj in C[node]:
        if not visited[adj]:
            DFS(adj)
    ans.appendleft(node)


for i in range(V):
    if not visited[i]:
        DFS(i)


for node in ans:
    print(node)

Solution (Python):









import os
import sys




def main():
    v,e = map(int,input().split())
    path_list = [[] for _ in range(v)]
    to_there = [0]*v
    for _ in range(e):
        s,t = map(int,input().split())
        path_list[s].append(t)
        to_there[t]+=1

    stack_list = [i for i,x in enumerate(to_there) if x==0]

    while stack_list:
        u = stack_list.pop()
        for v in path_list[u]:
            to_there[v]-=1
            if to_there[v]==0:
                stack_list.append(v)
        print(u)


if __name__ == "__main__":
    main()

Solution (Python):
from collections import deque
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
G = [[] for _ in [0]*N]
deg = [0]*N
for _ in [0]*M:
    a, b = map(int, input().split())
    G[a].append(b)
    deg[b] += 1

q = deque()

for v, d in enumerate(deg):
    if d == 0:
        print(v)
        q.append(v)

while q:
    v = q.popleft()
    for u in G[v]:
        deg[u] -= 1
        if deg[u] == 0:
            print(u)
            q.append(u)

Solution (Python):
import queue

V, E = map(int, input().split())

G = [[] for _ in range(V)]
visited = [False] * V
indeg = [0] * V
out = []

for _ in range(E):
    s, t = map(int, input().split())
    G[s].append(t)

for i in range(V):
    for j in range(len(G[i])):
        indeg[G[i][j]] += 1

q = queue.Queue()
for i in range(V):
    if indeg[i] == 0 and not visited[i]:
        q.put(i)
        visited[i] = True
        while not q.empty():
            u = q.get()
            out.append(u)
            for j in range(len(G[u])):
                v = G[u][j]
                indeg[v] -= 1
                if indeg[v] == 0 and not visited[v]:
                    visited[v] = True
                    q.put(v)

for el in out:
    print(el)

Solution (Python):
import sys,collections
V,E = tuple(map(int,sys.stdin.readline().split())) 

INF = float("inf")

st = tuple(tuple(map(int,sys.stdin.readline().rstrip().split())) for _ in range(E)) 

G = [[] for _ in range(V)]

for s,t in st:
    G[s].append(t)

visited = set()
indeg = [0]*V
ret = []
def bfs(s):
    q = collections.deque([s])
    visited.add(s)
    while q:
        u = q.popleft()
        ret.append(u)
        for v in G[u]:
            indeg[v] -= 1
            if indeg[v] == 0 and not v in visited:
                visited.add(v)
                q.append(v)

def topologicalSort_bfs():
    for a in G:
        for t in a:
            indeg[t] += 1
    
    for i in range(V):
        if indeg[i] == 0 and not i in visited:
            bfs(i)

def dfs(s):
    
    if s in visited:
        return
    for e in G[s]:
        dfs(e)
    ret.append(s)
    visited.add(s)

def topologicalSort_dfs():
    for i in range(V):
        dfs(i)
    ret.reverse()

topologicalSort_bfs()

print(*ret,sep='\n')

Solution (Python):
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate, product, combinations_with_replacement
import sys
import bisect
import string
import math
import time

def I(): return int(input())
def S(): return input()
def MI(): return map(int, input().split())
def MS(): return map(str, input().split())
def LI(): return [int(i) for i in input().split()]
def LI_(): return [int(i)-1 for i in input().split()]
def StoI(): return [ord(i)-97 for i in input()]
def ItoS(nn): return chr(nn+97)
def input(): return sys.stdin.readline().rstrip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

yn = {False: 'No', True: 'Yes'}
YN = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**19
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
show_flg = False



def main():
    V, E = MI()
    edges = []

    for i in range(E):
        edges.append(tuple(MI()))

    in_cnt = defaultdict(int)
    outs = defaultdict(list)
    for a, b in edges:
        in_cnt[b] += 1
        outs[a].append(b)

    res = []
    queue = deque([i for i in range(V) if in_cnt[i] == 0])
    while len(queue) != 0:
        v = queue.popleft()
        res.append(v)
        for nxt_v in outs[v]:
            in_cnt[nxt_v] -= 1
            if in_cnt[nxt_v] == 0:
                queue.append(nxt_v)

    for i in range(V):
        print(res[i])

if __name__ == '__main__':
    main()

Solution (Python):
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7 
input=lambda:sys.stdin.readline().rstrip()
res = []
def recursion(v, E, state) -> bool:
    
    if state[v]:
        return state[v] == 1
    
    state[v] = -1
    flag = all(recursion(nv, E, state) for nv in E[v])
    if flag:
        state[v] = 1
        res.append(v)
    return flag

def resolve():
    n, m = map(int,input().split())
    E = [[] for _ in range(n)]
    for _ in range(m):
        u, v = map(int,input().split())
        E[u].append(v)
    state = [0] * n 
    for v in range(n):
        recursion(v, E, state)
    print(*res[::-1], sep = '\n')
resolve()

Solution (Python):
from collections import deque
N,E=map(int,input().split())
G=[[] for i in range(N)]
In=[0]*N
for i in range(E):
    s,t=map(int,input().split())
    G[s].append(t)
    In[t]+=1
S=deque([i for i in range(N) if In[i]==0])
res=[]
while S:
    b=S.popleft()
    for nv in G[b]:
        In[nv]-=1
        if(In[nv]==0):
            S.append(nv)
    res.append(b)
print(*res,sep='\n')

Solution (Python):
from collections import deque

V, E = list(map(int, input().split()))
edge = [[] for i in range(V)]
in_num = [0] * V

for i in range(E):
    s, t = list(map(int, input().split()))
    edge[s].append(t)
    in_num[t] += 1
    
q = deque()

for i in range(V):
    if in_num[i] == 0: q.append(i)

ans = deque()

while q:
    v = q.popleft()
    
    ans.append(v)
    
    for u in edge[v]:
        in_num[u] -= 1
        if in_num[u] == 0: q.append(u)
        
for a in ans: print(a)

Solution (Python):
n,m = map(int,input().split())
G = [[] for i in range(n)]
deg = [0 for _ in range(n)]
for i in range(m):
    a,b = map(int,input().split())
    G[b].append(a)
    deg[a] += 1

from collections import deque
q = deque()
add,pop=q.append,q.popleft
for i in range(n):
    if deg[i]==0:
        add(i)

order = []
while q:
    v = pop()
    order.append(v)
    for nv in G[v]:
        deg[nv] -= 1
        if deg[nv] == 0:
            add(nv)

for i in order[::-1]:
    print(i)

Solution (Python):

from collections import deque


N, M = map(int, input().split())


G = [[] for _ in range(N)]
deg = [0]*N 
for i in range(M):
    a, b = map(int, input().split())
    G[b].append(a) 
    deg[a]+=1 


que = deque()
for i in range(N):
    if deg[i] == 0:
        que.append(i)


order = []
while len(que)!=0:
    
    v = que.popleft()
    order.append(v)

    
    for nv in G[v]:
        
        deg[nv]-=1

        
        if deg[nv] == 0:
            que.append(nv)


order.reverse()
for i in order:
    print(i)