Skip to content

Latest commit

 

History

History
34 lines (27 loc) · 670 Bytes

2252.md

File metadata and controls

34 lines (27 loc) · 670 Bytes

2252

Python

import heapq

N, M = map(int, input().split())
indegree_lst = [0 for _ in range(N+1)]
graph = [[] for _ in range(N+1)]
for _ in range(M):
    A, B = map(int, input().split())
    graph[A].append(B)
    indegree_lst[B] += 1

def topology_sort():
    result = []
    heap = []
    for i in range(1, N+1):
        if indegree_lst[i] == 0:
            heapq.heappush(heap, i)

    while heap:
        now = heapq.heappop(heap)
        result.append(now)
        for i in graph[now]:
            indegree_lst[i] -= 1
            if indegree_lst[i] == 0:
                heapq.heappush(heap, i)
    
    return result

print(*topology_sort())