Algorithm/BOJ
[백준] 2623번 - 음악프로그램 (파이썬)
_temp
2022. 2. 4. 23:25
# 음악프로그램
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
front = [0] * (N+1)
arr = [[] for _ in range(N+1)]
for i in range(1, M+1):
temp = list(map(int, input().split()))
for j in range(1, temp[0]):
arr[temp[j]].append(temp[j+1])
front[temp[j+1]] += 1
result = []
for _ in range(N):
for i in range(1, N+1):
if front[i] == 0 and i not in result:
result.append(i)
for j in range(len(arr[i])):
front[arr[i][j]] -= 1
if len(result) == N:
print(*result, sep='\n')
else:
print('0')
위상정렬
1. front(자신보다 앞에 있어야하는 수)를 1씩 더해주면서 입력을 받는다
2. result에 front가 0인 수부터 차례대로 append하고 그 수가 앞에 있는 모든 수들의 front -= 1 을 반복
3. result의 길이가 N이면 출력 아니면 0 출력