1766번: 문제집
첫째 줄에 문제의 수 N(1 ≤ N ≤ 32,000)과 먼저 푸는 것이 좋은 문제에 대한 정보의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 둘째 줄부터 M개의 줄에 걸쳐 두 정수의 순서쌍 A,B가 빈칸을 사이에 두고 주
www.acmicpc.net
import sys
import heapq
# 문제 푸는 순서 결정하기 => 위상정렬 (진입차수가 0인 정점을 큐에 추가)
def search(N, indgree):
res = []
qu = []
for i in range(1, N+1):
if indgree[i] == 0:
heapq.heappush(qu, i)
while qu:
node = heapq.heappop(qu)
res.append(node)
for e in graph[node]:
indgree[e] -= 1
if indgree[e] == 0:
heapq.heappush(qu, e) # 힙을 이용하므로 쉬운 문제 순서로 추출된다
return res
N, M = map(int, input().split())
graph = [[] for _ in range(N + 1)]
indgree = [0] * (N + 1)
for _ in range(M):
x, y = map(int, sys.stdin.readline().split())
graph[x].append(y)
indgree[y] += 1
ans = search(N, indgree)
[print(x, end=" ") for x in ans]
'BOJ 알고리즘 (패캠) > 정렬, 탐색' 카테고리의 다른 글
1715번: 카드 정렬하기 (힙) - Fastcampus (0) | 2020.10.07 |
---|---|
1927번: 최소 힙 (힙) - Fastcampus (0) | 2020.10.07 |
2250번: 트리의 높이와 너비 (트리, 재귀) - Fastcampus (0) | 2020.10.07 |
1991번: 트리 순회 (트리, 재귀) - Fastcampus (0) | 2020.10.07 |
1939번: 중량제한 (탐색, 이분탐색, BFS) - Fastcampus (0) | 2020.10.07 |