위상 정렬을 이용해 현재 접근 가능한 수 중 가장 작은 값을 출력한다
혹시나 나처럼 헷갈리는 이들이 있을까 싶어 문제 조건을 확실히 해두고 싶다.
M 중에 2 1 6 1 이런 조건이 있다면 2, 6을 순서대로 해결하고 1로 돌아오는 것이 아니라 매 순간 접근 할 수 있는 (선행 문제가 풀려 있는) 문제 중 번호가 가장 작은 순서를 출력하면 된다.
참고: 백준 질문 게시판
import sys
from queue import PriorityQueue
input = sys.stdin.readline
N, M = list(map(int, input().split()))
graph = [[] for _ in range(N + 1)]
prev_link_cnt = [0] * (N + 1)
for _ in range(M):
a, b = list(map(int, input().strip().split()))
graph[a].append(b)
prev_link_cnt[b] += 1
q = PriorityQueue()
for i in range(1, N + 1):
if prev_link_cnt[i] == 0:
q.put(i)
while(q.qsize() > 0):
c = q.get()
for item in graph[c]:
prev_link_cnt[item] -= 1
if prev_link_cnt[item] == 0:
q.put(item)
sys.stdout.write(str(c) + " ")