forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path6.py
43 lines (36 loc) Β· 1.38 KB
/
6.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from collections import deque
# λ
Έλμ κ°μμ κ°μ μ κ°μλ₯Ό μ
λ ₯ λ°κΈ°
v, e = map(int, input().split())
# λͺ¨λ λ
Έλμ λν μ§μ
μ°¨μλ 0μΌλ‘ μ΄κΈ°ν
indegree = [0] * (v + 1)
# κ° λ
Έλμ μ°κ²°λ κ°μ μ 보λ₯Ό λ΄κΈ° μν μ°κ²° 리μ€νΈ μ΄κΈ°ν
graph = [[] for i in range(v + 1)]
# λ°©ν₯ κ·Έλνμ λͺ¨λ κ°μ μ 보λ₯Ό μ
λ ₯ λ°κΈ°
for _ in range(e):
a, b = map(int, input().split())
graph[a].append(b) # μ μ Aμμ Bλ‘ μ΄λ κ°λ₯
# μ§μ
μ°¨μλ₯Ό 1 μ¦κ°
indegree[b] += 1
# μμ μ λ ¬ ν¨μ
def topology_sort():
result = [] # μκ³ λ¦¬μ¦ μν κ²°κ³Όλ₯Ό λ΄μ 리μ€νΈ
q = deque() # ν κΈ°λ₯μ μν deque λΌμ΄λΈλ¬λ¦¬ μ¬μ©
# μ²μ μμν λλ μ§μ
μ°¨μκ° 0μΈ λ
Έλλ₯Ό νμ μ½μ
for i in range(1, v + 1):
if indegree[i] == 0:
q.append(i)
# νκ° λΉ λκΉμ§ λ°λ³΅
while q:
# νμμ μμ κΊΌλ΄κΈ°
now = q.popleft()
result.append(now)
# ν΄λΉ μμμ μ°κ²°λ λ
Έλλ€μ μ§μ
μ°¨μμμ 1 λΉΌκΈ°
for i in graph[now]:
indegree[i] -= 1
# μλ‘κ² μ§μ
μ°¨μκ° 0μ΄ λλ λ
Έλλ₯Ό νμ μ½μ
if indegree[i] == 0:
q.append(i)
# μμ μ λ ¬μ μνν κ²°κ³Ό μΆλ ₯
for i in result:
print(i, end=' ')
topology_sort()