forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path9.py
More file actions
47 lines (40 loc) Β· 1.53 KB
/
9.py
File metadata and controls
47 lines (40 loc) Β· 1.53 KB
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
44
45
46
47
from collections import deque
import copy
# λ
Έλμ κ°μ μ
λ ₯λ°κΈ°
v = int(input())
# λͺ¨λ λ
Έλμ λν μ§μ
μ°¨μλ 0μΌλ‘ μ΄κΈ°ν
indegree = [0] * (v + 1)
# κ° λ
Έλμ μ°κ²°λ κ°μ μ 보λ₯Ό λ΄κΈ° μν μ°κ²° 리μ€νΈ(κ·Έλν) μ΄κΈ°ν
graph = [[] for i in range(v + 1)]
# κ° κ°μ μκ°μ 0μΌλ‘ μ΄κΈ°ν
time = [0] * (v + 1)
# λ°©ν₯ κ·Έλνμ λͺ¨λ κ°μ μ 보λ₯Ό μ
λ ₯λ°κΈ°
for i in range(1, v + 1):
data = list(map(int, input().split()))
time[i] = data[0] # 첫 λ²μ§Έ μλ μκ° μ 보λ₯Ό λ΄κ³ μμ
for x in data[1:-1]:
indegree[i] += 1
graph[x].append(i)
# μμ μ λ ¬ ν¨μ
def topology_sort():
result = copy.deepcopy(time) # μκ³ λ¦¬μ¦ μν κ²°κ³Όλ₯Ό λ΄μ 리μ€νΈ
q = deque() # ν κΈ°λ₯μ μν deque λΌμ΄λΈλ¬λ¦¬ μ¬μ©
# μ²μ μμν λλ μ§μ
μ°¨μκ° 0μΈ λ
Έλλ₯Ό νμ μ½μ
for i in range(1, v + 1):
if indegree[i] == 0:
q.append(i)
# νκ° λΉ λκΉμ§ λ°λ³΅
while q:
# νμμ μμ κΊΌλ΄κΈ°
now = q.popleft()
# ν΄λΉ μμμ μ°κ²°λ λ
Έλλ€μ μ§μ
μ°¨μμμ 1 λΉΌκΈ°
for i in graph[now]:
result[i] = max(result[i], result[now] + time[i])
indegree[i] -= 1
# μλ‘κ² μ§μ
μ°¨μκ° 0μ΄ λλ λ
Έλλ₯Ό νμ μ½μ
if indegree[i] == 0:
q.append(i)
# μμ μ λ ¬μ μνν κ²°κ³Ό μΆλ ₯
for i in range(1, v + 1):
print(result[i])
topology_sort()