문제풀이/그래프

[파이썬] [그래프] 백준 2252 줄 세우기

승무_ 2022. 2. 8. 01:42

문제

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

 

2252번: 줄 세우기

첫째 줄에 N(1 ≤ N ≤ 32,000), M(1 ≤ M ≤ 100,000)이 주어진다. M은 키를 비교한 회수이다. 다음 M개의 줄에는 키를 비교한 두 학생의 번호 A, B가 주어진다. 이는 학생 A가 학생 B의 앞에 서야 한다는 의

www.acmicpc.net

코드

import sys
from collections import deque
input=sys.stdin.readline

def sort():
    queue=deque()
    for i in range(1,n+1):
        if parent[i]==0:
            queue.append(i)
    while queue:
        x=queue.popleft()
        result.append(x)

        for i in array[x]:
            parent[i]-=1
            if parent[i]==0:
                queue.append(i)

n,m=map(int, input().split())
parent=[0]*(n+1)
array=[[] for _ in range(n+1)]

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

result=[]
sort()

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