문제  

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

 

문제풀이

답이 여러개 이기때문에 위상정렬을 해주는 것 말고는 딱히 어려운 부분이 없다

 

코드

from collections import deque
import collections

v, e = map(int,input().split())

#진입차수 처리할 리스트
indegree = [0] *(v+1)

#그래프 생성
graph = collections.defaultdict(list)

for i in range(e):

    a,b= map(int,input().split())
    graph[a].append(b)

    # 키가 더큰 아이는 진입차수 +1
    indegree[b] +=1


# 위상정렬  

q = deque()

# 진입차수가 0인 노드 넣기
for i in range(1,v+1):
    if indegree[i] ==0 :
        q.append(i)


result = []    
while q :

    node= q.popleft()

    result.append(node)

    for a in graph[node]:
        indegree[a] -=1

        # 진입차수가 0이되면 q에 append
        if indegree[a] == 0:
            q.append(a)

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

'파이썬 > 백준' 카테고리의 다른 글

[python] 백준 -최단 경로  (0) 2021.01.07
[python] 백준 -잃어버린 괄호  (0) 2021.01.07
[python] 백준 -가장 긴 단어  (0) 2021.01.07
[python] 백준 -Z  (0) 2021.01.07
[python] 백준 - 트리순회.py  (0) 2021.01.07
ariz1623