[백준] 2252번 줄 세우기

JaeYeop·2022년 4월 13일
0

백준

목록 보기
11/19

[문제]

https://www.acmicpc.net/problem/2252

[코드]

from collections import deque

n, m = map(int, input().split())
graph = [[] for i in range(n + 1)]
indegree = [0] * (n + 1)
for i in range(m):
    a, b = map(int, input().split())
    graph[a].append(b)
    indegree[b] += 1

q = deque()
for i in range(1, n + 1):
    if indegree[i] == 0:
        q.append(i)

result = []
while q:
    now = q.popleft()
    result.append(now)
    for i in graph[now]:
        indegree[i] -= 1
        if indegree[i] == 0:
            q.append(i)


for i in result:
    print(i, end=' ')

[풀이]

이 문제는 위상 정렬을 이용하면 손쉽게 해결할 수 있다

위상 정렬은 큐로 구현하며, indegree가 0일 경우 큐에 넣어 문제를 풀어나간다

profile
이게 왜 틀리지... (나의 메모용 블로그)

0개의 댓글