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 zadanie_2():

    
    [n, m] = list(map(int, input().strip().split(" ")))

    sasiedzi = [[] for _ in range(n)]
    stopnie = [0 for _ in range(n)]
    kolejka = []
    kolejnosc = []

    for i in range(m):
        luk = list(map(int, input().strip().split(" ")))
        sasiedzi[luk[0]].append(luk[1])
        stopnie[luk[1]] += 1

    for i in range(n):
        if stopnie[i] == 0:
            kolejka.append(i)

    while len(kolejka) > 0:
        wierzcholek = kolejka.pop(0)
        kolejnosc.append(wierzcholek)
        for sasiad in sasiedzi[wierzcholek]:
            stopnie[sasiad] -= 1
            if stopnie[sasiad] == 0:
                kolejka.append(sasiad)

    for i in range(len(kolejnosc)):
        print(str(kolejnosc[i]), end="")
        if i < len(kolejnosc) - 1:
            print("")


zadanie_2()

Solution (Python):
from collections import deque

v, e = map(int,input().split())
edges = [[] for _ in range(v)]
in_num = [0 for _ in range(v)]

for _ in range(e):
    s,t = map(int, input().split())
    edges[s].append(t)
    in_num[t] += 1

q = deque()

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

ans = []
while q:
    node = q.popleft()
    ans.append(node)
    for v in edges[node]:
        in_num[v] -= 1
        if in_num[v] == 0:
            q.append(v)

for i in ans:
    print(i)

Solution (Python):
from collections import deque


def topologicalSort(v,e):
    global color,out,indeg
    color=["white" for _ in range(v)]
    indeg=[[0,[]] for _ in range(v)]
    out=[]

    for i in range(e):
        s,t=map(int,input().split())
        indeg[s][0] +=1
        indeg[t][1] +=[s]

    for i in range(v):
        if indeg[i][0]==0 and color[i]=="white":
            BFS(i)

    return out[::-1]


def BFS(s):
    Q=deque([])
    Q.append(s)
    color[s]="gray"
    while len(Q)!=0:
        u=Q.popleft()
        out.append(u)

        for i in indeg[u][1]:
            indeg[i][0] -=1
            if indeg[i][0]==0 and color[i]=="white":
                color[i]="gray"
                Q.append(i)


v,e=map(int,input().split())
for i in topologicalSort(v,e):
    print(i)

Solution (Python):
from collections import defaultdict, deque

v, n = map(int, input().split())
es = [[int(x) for x in input().split()] for _ in range(n)]

outs = defaultdict(list)
ins = defaultdict(int)
for v1, v2 in es:
    outs[v1].append(v2)
    ins[v2] += 1

q = deque(v1 for v1 in range(v) if ins[v1] == 0)
res = []
while q:
    v1 = q.popleft()
    res.append(v1)
    for v2 in outs[v1]:
        ins[v2] -= 1
        if ins[v2] == 0:
            q.append(v2)

for i in res:
    print(i)

Solution (Python):
from collections import deque
from collections import defaultdict
V, E = map(int, input().split())
d = [0]*V
G = defaultdict(list)
for i in range(E):
    s, t = map(int, input().split())
    d[t] += 1
    G[s].append(t)
q = deque([])
for i in range(V):
    if d[i] == 0:
        q.append(i)
ans = []
while q:
    s = q.popleft()
    ans.append(s)
    for t in G[s]:
        d[t] -= 1
        if d[t] == 0:
            q.append(t)
for x in ans:
    print(x)

Solution (Python):
import sys
from collections import deque

def topologicalSort():
    input = sys.stdin.readline
    V, E = map(int, input().split())
    Parent_node = [0 for _ in range(V)]
    Son_node = [set() for _ in range(V)]
    for _ in range(E):
        a, b = map(int, input().split()) 
        Son_node[a] |= {b}
        Parent_node[b] += 1

    stack = deque() 
    for i, p in enumerate(Parent_node):
        if p == 0: stack.append(i)

    sortedArray = []
    while stack:
        nowNode = stack.popleft()
        sortedArray.append(nowNode)
        for nextNode in Son_node[nowNode]:
            Parent_node[nextNode] -= 1
            if Parent_node[nextNode] == 0: stack.append(nextNode)

    for a in sortedArray: print(a)

    return len(sortedArray) == V

if __name__ == "__main__":
    topologicalSort()

Solution (Python):
from collections import deque


def topological_sort(indeg, tonodes, v):
    nodes = deque([])
    visited = deque([])
    for i in range(v):
        if indeg[i] == 0:
            nodes.append(i)
    while len(nodes) > 0:
        i = nodes.popleft()
        visited.append(i)
        for j in tonodes[i]:
            indeg[j] -= 1
            if indeg[j] == 0:
                nodes.append(j)
    return visited


def main():
    ve = input().split()
    v, e = tuple(map(int, ve))
    indeg = [0 for _ in range(v)]
    tonodes = [[] for _ in range(v)]

    for _ in range(e):
        st = input().split()
        s, t = tuple(map(int, st))
        indeg[t] += 1
        tonodes[s].append(t)
    visited = topological_sort(indeg, tonodes, v)
    while len(visited) > 0:
        print(visited.popleft())


if __name__ == "__main__":
    main()

Solution (Python):
from collections import deque

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

dic = {}
pnum = [0] * V

for i in range(E):

    s,t = map(int,input().split())

    pnum[t] += 1
    
    if s not in dic:
        dic[s] = []
    dic[s].append(t)

q = deque([])
ans = []

for i in range(V):

    if pnum[i] == 0:
        q.append(i)
        ans.append(i)

while len(q) > 0:

    now = q.popleft()

    if now not in dic:
        continue

    for i in dic[now]:
        pnum[i] -= 1

        if pnum[i] == 0:
            q.append(i)
            ans.append(i)

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

Solution (Python):
def topologicalSort(g: list, deg: list):
	ret = []
	q = []
	for i, d in enumerate(deg):
		if not d:
			ret.append(i)
			q.append(i)
	while q:
		cur = q.pop(0)
		for nxt in g[cur]:
			deg[nxt] -= 1
			if not deg[nxt]:
				ret.append(nxt)
				q.append(nxt)
	return ret

def main():
	v, e, *L = map(int, open(0).read().split())
	g = [[] for _ in range(v)]
	deg = [0] * v
	for s, t in zip(*[iter(L)] * 2):
		g[s].append(t)
		deg[t] += 1
	print("\n".join(map(str, topologicalSort(g, deg))))

if __name__ == "__main__":
	main()

Solution (Python):

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

adjacents = []

for i in range(V):
  adjacents.append([])

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

def topological_sort(num, adjacents):
  colors = ["white"] * num
  result = []

  def dfs(u):
    if colors[u] == "black":
      return

    colors[u] = "black"

    for a in adjacents[u]:
      if colors[a] != "black":
        dfs(a)

    result.append(u)

  for n in range(num):
    dfs(n)

  return result

for i in topological_sort(V, adjacents):
  print(i)

Solution (Python):



import queue

WHITE = 0
GRAY = 1
BLACK= 2

def topologicalSort(s):
    Q.put(s)
    color[s] = GRAY
    while not Q.empty():
        u = Q.get()
        out.append(u)
        
        for v in G[u]:
            indeg[v] -= 1
            if indeg[v] == 0 and color[v] == WHITE:
                color[v] = GRAY
                Q.put(v)
            



nums=list(map(int,input().split()))
n = nums[0]
e = nums[1]

color = [WHITE] * n
G = [[] for i in range(n)]
indeg = [0] * n

for i in range(e):
    nums=list(map(int,input().split()))
    G[nums[0]].append(nums[1])
    indeg[nums[1]] += 1

Q = queue.Queue()
out = []

for i in range(n):
    if indeg[i] == 0 and color[i] == WHITE:
        topologicalSort(i)

for i in range(n):
    print(out[i])

Solution (Python):

import sys
import collections
input = lambda: sys.stdin.buffer.readline()[:-1].decode('utf-8')
sys.setrecursionlimit(10**8)
inf = float('inf')
mod = 10**9+7

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

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



def Topological_Sort(G):
    
    V=len(G)
    div=[0]*V
    for gi in G:
        for ei  in gi:
            div[ei]+=1
    used=[0]*V
    result=[]

    def bfs(node):
        que = collections.deque([node])
        used[node] = 1
        while que:
            tmp = que.popleft()
            result.append(tmp)
            for v in G[tmp]:
                div[v] -= 1
                if div[v] == 0 and not used[v]:
                    que.append(v)
                    used[v] = 1

    for i in range(V):
        if div[i]==0 and not used[i]:
            bfs(i)
    return result

    
ans=Topological_Sort(G)
print(*ans,sep="\n")

Solution (Python):
import sys
input = sys.stdin.readline
from operator import itemgetter
INF = 10**30
sys.setrecursionlimit(10000000)
from collections import deque
G = []
into = [] 


def topological_sort(n):
    global into
    ans = []
    unvisited = [True] * n
    for i in range(n):
        if into[i] == 0 and unvisited[i]:
            q = deque()
            q.append(i)
            while len(q) > 0:
                node = q.popleft()
                ans.append(node)
                unvisited[node] = False
                for v in G[node]:
                    into[v] -= 1
                    if into[v] == 0:
                        q.append(v)
    return ans

visited = []
answer = deque()
def rec(v):
    global visited
    visited[v] = True

    for node in G[v]:
        if not visited[node]:
            rec(node)
    answer.appendleft(v)

def dfs_topolo(n):
    for i in range(n):
        if not visited[i]:
            rec(i)

def main():
    global G, into, visited
    v, e = list(map(int, input().strip().split()))
    G = [[] for _ in range(v)]
    visited = [False] * v
    into = [0] * v
    for i in range(e):
        s, t = list(map(int, input().strip().split()))
        G[s].append(t)
        into[t] += 1
    
    
    
    dfs_topolo(v)
    for p in answer:
        print(p)

if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque

v,e = map(int,input().split())
L = []
ins = [0]*v
DAG = [[] for i in range(v)]
ans = []
for i in range(e):
    a,b = map(int,input().split())
    DAG[a].append(b)
    ins[b] += 1
start = 0
S = deque([])
for i in range(v):
    if ins[i] == 0:
        S.append(i)
while len(S) > 0:
    cur = S.popleft()
    ans.append(cur)
    for e in DAG[cur]:
        ins[e] -= 1
        if ins[e] == 0:
            S.append(e)
for i in range(v):
  print(ans[i])

Solution (Python):
Vnum = 0
Enum = 0
Edge = {}
L = []
V = []

def visit(n):
    if V[n] == 1:
        sys.exit()
    elif V[n] == 0:
        V[n] = 1
        if n in Edge.keys():
            for m in Edge[n]:
                visit(m)
        V[n] = 2
        L.append(n)
        return True

Vnum,Enum = map(int,input().split())
V = [ 0 for v in range(Vnum) ]
for _ in range(Enum):
    s,t = map(int,input().split())
    if s in Edge.keys():
        Edge[s].append(t)
    else:
        Edge[s] = [t]


for n in range(Vnum):
    if V[n] == 0:
        visit(n)

L.reverse()
for a in L:
    print(a)

Solution (Python):


import os
import sys


def main():
    sys.setrecursionlimit(100000)
    V, E = read_ints()
    G = [set() for _ in range(V)]
    for _ in range(E):
        s, t = read_ints()
        G[s].add(t)
    print(*solve(V, E, G), sep='\n')


def solve(V, E, G):
    topo = []
    done = [False] * V

    def dfs(i):
        if done[i]:
            return
        for j in G[i]:
            dfs(j)
        done[i] = True
        topo.append(i)

    for i in range(V):
        if not done[i]:
            dfs(i)

    topo.reverse()
    return topo





DEBUG = 'DEBUG' in os.environ


def inp():
    return sys.stdin.readline().rstrip()


def read_int():
    return int(inp())


def read_ints():
    return [int(e) for e in inp().split()]


def dprint(*value, sep=' ', end='\n'):
    if DEBUG:
        print(*value, sep=sep, end=end)


if __name__ == '__main__':
    main()

Solution (Python):
from typing import List, Tuple

def topological_sort(n: int, m: int, G: List[List[int]]) -> List[int]:
	for u in range(n):
		if color[u] == "WHITE":
			dfs(u)
	return L[::-1]

def dfs(u: int) -> None:
	if color[u] == "GRAY":
		print("Graph is not DAG")
		exit()
	if color[u] == "BLACK":
		return
	color[u] = "GRAY"
	for v in G[u]:
		dfs(v)
	color[u] = "BLACK"
	L.append(u)


if __name__ == "__main__":
	n, m = map(int, input().split())
	G = [[] for _ in range(n)]
	color: List[str] = ["WHITE" for _ in range(n)]
	L: List[int] = []
	for _ in range(m):
		s, t = map(int, input().split())
		G[s].append(t)
	L = topological_sort(n, m, G)
	for v in L:
		print(v)

Solution (Python):

import sys



v, e = map(int, sys.stdin.readline().strip().split())
G = [[] for _ in range(v)]
indeg = [0] * v
for i in range(e):
    s, t = map(int, sys.stdin.readline().strip().split())
    G[s].append(t)
    indeg[t] += 1



ans = []


def dfs(u):
    if indeg[u] == 0:
        ans.append(u)
        for i in G[u]:
            indeg[i] -= 1
            dfs(i)


indeg_start = indeg.copy()
for i in range(v):
    if indeg_start[i] == 0:  
        dfs(i)


for i in ans:
    print(i)

Solution (Python):

def topological_sort(nodes, edges) -> []:
    visited = set()
    result = []

    def dfs(v):
        if v not in visited:
            visited.add(v)
            for u in edges[v]:
                dfs(u)
            result.append(v)

    for s in nodes:
        dfs(s)

    return result

def aoj_system_test():
    """
    The problem of aoj for topological sort use special judge.
    So, I can't verify using online-judge-tools. (T T)
    """
    V, E = map(int, input().split())
    nodes = []
    edges = []
    for i in range(V):
        nodes.append(i)
        edges.append([])
    for _ in range(E):
        a, b = map(int, input().split())
        edges[b].append(a)
    ret = topological_sort(nodes, edges)
    for v in ret:
        print(v)

if __name__ == '__main__':
    aoj_system_test()

Solution (Python):
from collections import defaultdict, deque


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

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


s_dic = {}


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


for s,e in se_list:
    if s in s_dic:
        s_dic[s].append(e)
    else:
        s_dic[s] = [e]
    e_list[e] += 1


dfs_q = deque()
for v in range(V):
    if e_list[v] == 0:
        dfs_q.append(v)


topological_sort = []


while dfs_q:
    v_from = dfs_q.pop()
    topological_sort.append(v_from)
    if v_from in s_dic:
        for v_to in s_dic[v_from]:
            e_list[v_to] -= 1
            if e_list[v_to] == 0:
                dfs_q.append(v_to)


for v in topological_sort:
    print(v)

Solution (Python):
from collections import deque
v, e  = map(int, input().split())

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

Q= deque()

ans = []
for u in range(v):
    if not inDeg[u]:
        Q.append(u)

while Q:
    u = Q.popleft()
    ans.append(u)
    for t in Edg[u]:
        inDeg[t] -= 1
        if inDeg[t] == 0 and not Done[t]:
            Q.append(t)
            Done[t] = 1

    
for i in ans:
    print(i)

Solution (Python):
from collections import deque

def bfs(s):
  q = deque()
  q.append(s)
  while len(q) > 0:
    u = q.popleft()
    searched[u] = True
    res.append(u)
    for v in adj[u]:
      indeg[v] -= 1
      if indeg[v] == 0 and not searched[v]:
        q.append(v)

V, E = map(int, input().split())
adj = [[] for i in range(V)]
indeg = [0 for i in range(V)]

for i in range(E):
  u, v = map(int, input().split())
  adj[u].append(v)
  indeg[v] += 1

searched = [False for i in range(V)]
res = []

for u in range(V):
  if indeg[u] == 0 and not searched[u]:
    bfs(u)

for u in res:
  print(u)

Solution (Python):
from collections import deque


def topological_sort(graph: list) -> list:
    """入力した重みなしDAGに対してトポロジカルソートする
    計算量: O(|V|+|E|)
    入力条件: グラフGはDAGである、グラフGに多重辺はない、グラフGに自己ループはない
    """
    n = len(graph)
    degree = [0] * n
    for g in graph:
        for next_pos in g:
            degree[next_pos] += 1
    
    
    ans = [i for i in range(n) if degree[i] == 0]

    q = deque(ans)
    while q:
        pos = q.popleft()
        for next_pos in graph[pos]:
            degree[next_pos] -= 1
            if degree[next_pos] == 0:
                q.append(next_pos)
                ans.append(next_pos)
    return ans

n, m = map(int, input().split())
info = [list(map(int, input().split())) for i in range(m)]
graph = [[] for i in range(n)]
for i in range(m):
    a, b = info[i]
    graph[a].append(b)
ans = topological_sort(graph)
for pos in ans:
    print(pos)

Solution (Python):
import sys

sys.setrecursionlimit(200000)


def dfs(i: int) -> None:
    global visited, edges, counter, finish_order
    visited[i] = True
    for edge in edges[i]:
        if visited[edge]:
            continue
        dfs(edge)
    finish_order[i] = (counter, i)
    counter += 1


if __name__ == "__main__":
    V, E = map(int, input().split())
    edges = [set() for _ in range(V)]  

    for _ in range(E):
        s, t = map(lambda x: int(x), input().split())
        edges[s].add(t)

    visited = [False] * V
    finish_order = [(0, 0)] * V
    counter = 0

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

    for d, i in sorted(finish_order, reverse=True):  
        print(i)

Solution (Python):











import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,log 
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    N,M = MI()
    edge = [[]for _ in range(N)]
    indegree = [0]*N 
    for _ in range(M):
        a,b = MI()
        edge[a].append(b)
        indegree[b] += 1
    
    
    queue = deque() 
    for i,x in enumerate(indegree):
        if not x:
            queue.append(i)

    pop = queue.popleft
    topological_index = []
    while queue:
        v = pop()
        topological_index.append(v)

        for to in edge[v]:
            indegree[to] -= 1
            if not indegree[to]:
                queue.append(to)
    if tuple(1 for i in indegree if i!=0):
        print("loop")

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



if __name__ == '__main__':
    main()

Solution (Python):
from collections import defaultdict, deque

v, n = map(int, input().split())  
es = [[int(x) for x in input().split()] for _ in range(n)]

outs = defaultdict(list)
ins = defaultdict(int)
for v1, v2 in es:
    outs[v1].append(v2)
    ins[v2] += 1

q = deque(v1 for v1 in range(v) if ins[v1] == 0)
res = []
while q:
    v1 = q.popleft()
    res.append(v1)
    for v2 in outs[v1]:
        ins[v2] -= 1
        if ins[v2] == 0:
            q.append(v2)

for i in res:
    print(i)

Solution (Python):
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7


def topological_sort(graph):
    """
    :param list of (list of int) graph:
    :return:
    """
    
    ins = [0] * len(graph)
    for vs in graph:
        for v in vs:
            ins[v] += 1

    
    zeros = []
    for v, cnt in enumerate(ins):
        if cnt == 0:
            zeros.append(v)

    
    ret = []
    while zeros:
        v = zeros.pop()
        ret.append(v)
        for u in graph[v]:
            ins[u] -= 1
            if ins[u] == 0:
                zeros.append(u)
    return ret


V, E = list(map(int, sys.stdin.readline().split()))
ST = [list(map(int, sys.stdin.readline().split())) for _ in range(E)]

graph = [[] for _ in range(V)]
for s, t in ST:
    graph[s].append(t)

ans = topological_sort(graph)
print(*ans, sep='\n')

Solution (Python):
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(input())
def inpl(): return list(map(int, input().split()))
def inpl_str(): return list(input().split())

N,M = inpl()
lines = defaultdict(set)
hh = [0]*N
for _ in range(M):
    x,y = inpl()
    lines[x].add(y)
    hh[y] += 1

q = queue.Queue()
for t in range(N):
    if hh[t] == 0:
        q.put(t)

topological = []
while not q.empty():
    s = q.get()
    topological.append(s)
    for t in lines[s]:
        hh[t] -= 1
        if hh[t] == 0:
            q.put(t)

for x in topological:
    print(x)

Solution (Python):
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
Max = sys.maxsize
def l(): 
	return list(map(int,input().split()))
def m(): 
	return map(int,input().split())
def onem(): 
	return int(input())
def s(x): 
	a = []
	aa = x[0]
	su = 1
	for i in range(len(x)-1):
		if aa == x[i+1]:
			a.append([aa,su])
			aa = x[i+1]
			su = 1
		else:
			su += 1
	a.append([aa,su])
	return a
def jo(x): 
	return " ".join(map(str,x))
def max2(x): 
	return max(map(max,x))

def Topo_sort(x,y):
	co = cl.Counter(n for m in x.values() for n in m)
	S = cl.deque([i for i in range(y) if co[i] == 0])
	while S:
		n = S.popleft()
		yield n
		for i in x[n]:
			co[i] -= 1
			if co[i] <= 0:
				S.append(i)


v,e = m()

g = cl.defaultdict(set)

for i in range(e):
	s,t = m()
	g[s] |= {t}
a = Topo_sort(g,v)

for i in Topo_sort(g,v):
	print(i)

Solution (Python):
v, e = map(int, input().split())
indeg = [0]*v
uv = [[] for _ in range(v)]
for i in range(e):
    s, t = map(int, input().split())
    uv[s].append(t)
    indeg[t] += 1

'''
topologicalSort
トポロジカルソート
'''
visited = [False]*v
ans = []
for i in range(v):
    if indeg[i] == 0 and not visited[i]:
        q = [i]
        visited[i] = True
        while len(q) > 0:
            u = q.pop(0)
            ans.append(u)
            for v in uv[u]:
                indeg[v] -= 1
                if indeg[v] == 0 and not visited[v]:
                    visited[v] = True
                    q.append(v)

for v in ans:
    print(v)

Solution (Python):


from collections import deque

n, k = map(int, input().split())

a = [[] for i in range(n)]
in_num = [0]*n
for _ in range(k):
    p, q = map(int, input().split())
    a[p] += [q]
    in_num[q] += 1





color = [0]*n
result = deque()
aa = deque()

def topologicalSort_w(s):
    aa.append(s)
    color[s] = 1
    while aa:


        u = aa.popleft()
        result.append(u)
        for v in a[u]:
            in_num[v] -= 1
            if in_num[v] == 0 and color[v] == 0:
                color[v] = 1
                aa.append(v)
        

for i in range(n):
    if in_num[i] == 0 and color[i] == 0:
        topologicalSort_w(i)
        

                
for i in range(len(result)):
    print(result.popleft())

Solution (Python):
def input(f):
    V, E = map(int, f.readline().split())
    s = [None for _ in range(E)]
    t = [None for _ in range(E)]
    for i in range(E):
        s[i], t[i] = map(int, f.readline().split())
    return V, E, s, t

def solve(V, E, s, t):
    graph = [[] for _ in range(V)]
    for i in range(E):
        graph[s[i]].append(t[i])
    
    order = []
    used = [False for _ in range(V)]
    def visit(cur):
        if used[cur]:
            return
        used[cur] = True
        for nxt in graph[cur]:
            visit(nxt)
        order.append(cur)
    
    for i in range(V):
        visit(i)
    
    for v in reversed(order):
        print(v)

with open('/dev/stdin') as f:
    solve(*input(f))