Algorithm (PS)

[백준] 14567번: 선수과목 (Python/파이썬) - 위상정렬

minjiwoo 2022. 12. 11. 18:23
728x90

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

 

14567번: 선수과목 (Prerequisite)

3개의 과목이 있고, 2번 과목을 이수하기 위해서는 1번 과목을 이수해야 하고, 3번 과목을 이수하기 위해서는 2번 과목을 이수해야 한다.

www.acmicpc.net

진입차수가 0 이면 queue에 넣어주고, 
queue에서 빼서 현재 노드 탐색하고, 현재 노드에서 인접한 노드들의 진입차수를 1씩 뺸다. 
그리고 진입차수가 0이 되면 다시 queue에 넣어준다. 
현재 최소 학기를 구해야 하므로 , queue에 enqueue하는게 몇번째인지 세어주는 count 도 같이 넣어준다. 

from collections import deque

n, m = map(int, input().split())
graph = [[] for _ in range(n+1)]
indegree = [0] * (n+1) # 진입차수
result = [0] * (n+1)

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

def topology_sort():
    queue = deque()
    for i in range(1, n+1):
        if indegree[i] == 0:
            queue.append((i, 1))
            result[i] = 1
    while queue:
        now, count = queue.popleft()
        for i in graph[now]:
            indegree[i] -= 1
            result[i] += 1 # 1학기 추가
            if indegree[i] == 0:
                queue.append((i, count+1))
                result[i] = count+1

topology_sort()
print(*result[1:])
728x90