백준 2252 - 줄 세우기 (Python)

Updated:

위상정렬 알고리즘을 사용하면 됩니다.

전체 코드

import sys
from collections import deque

input = sys.stdin.readline

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

a = [list(map(int, input().split())) for _ in range(M)]
counts = [0 for i in range(32001)]
graph = [[] for i in range(32001)]
q = deque()

for i, j in a:
    graph[i].append(j)
    counts[j] += 1

for i in range(1, N + 1):
    if counts[i] == 0:
        q.append(i)

answer = []

while q:
    tmp = q.popleft()
    answer.append(tmp)
    
    for i in graph[tmp]:
        counts[i] -= 1
        if counts[i] == 0:
            q.append(i)

print(*answer)

Categories:

Updated: