forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path5.py
79 lines (71 loc) Β· 2.65 KB
/
5.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
from collections import deque
# ν
μ€νΈ μΌμ΄μ€(Test Case)λ§νΌ λ°λ³΅
for tc in range(int(input())):
# λ
Έλμ κ°μ μ
λ ₯ λ°κΈ°
n = int(input())
# λͺ¨λ λ
Έλμ λν μ§μ
μ°¨μλ 0μΌλ‘ μ΄κΈ°ν
indegree = [0] * (n + 1)
# κ° λ
Έλμ μ°κ²°λ κ°μ μ 보λ₯Ό λ΄κΈ° μν μΈμ νλ ¬ μ΄κΈ°ν
graph = [[False] * (n + 1) for i in range(n + 1)]
# μλ
μμ μ 보 μ
λ ₯
data = list(map(int, input().split()))
# λ°©ν₯ κ·Έλνμ κ°μ μ 보 μ΄κΈ°ν
for i in range(n):
for j in range(i + 1, n):
graph[data[i]][data[j]] = True
indegree[data[j]] += 1
# μ¬ν΄ λ³κ²½λ μμ μ 보 μ
λ ₯
m = int(input())
for i in range(m):
a, b = map(int, input().split())
# κ°μ μ λ°©ν₯ λ€μ§κΈ°
if graph[a][b]:
graph[a][b] = False
graph[b][a] = True
indegree[a] += 1
indegree[b] -= 1
else:
graph[a][b] = True
graph[b][a] = False
indegree[a] -= 1
indegree[b] += 1
# μμ μ λ ¬(Topology Sort) μμ
result = [] # μκ³ λ¦¬μ¦ μν κ²°κ³Όλ₯Ό λ΄μ 리μ€νΈ
q = deque() # ν κΈ°λ₯μ μν deque λΌμ΄λΈλ¬λ¦¬ μ¬μ©
# μ²μ μμν λλ μ§μ
μ°¨μκ° 0μΈ λ
Έλλ₯Ό νμ μ½μ
for i in range(1, n + 1):
if indegree[i] == 0:
q.append(i)
certain = True # μμ μ λ ¬ κ²°κ³Όκ° μ€μ§ νλμΈμ§μ μ¬λΆ
cycle = False # κ·Έλν λ΄ μ¬μ΄ν΄μ΄ μ‘΄μ¬νλμ§ μ¬λΆ
# μ νν λ
Έλμ κ°μλ§νΌ λ°λ³΅
for i in range(n):
# νκ° λΉμ΄ μλ€λ©΄ μ¬μ΄ν΄μ΄ λ°μνλ€λ μλ―Έ
if len(q) == 0:
cycle = True
break
# νμ μμκ° 2κ° μ΄μμ΄λΌλ©΄ κ°λ₯ν μ λ ¬ κ²°κ³Όκ° μ¬λ¬ κ°λΌλ μλ―Έ
if len(q) >= 2:
certain = False
break
# νμμ μμ κΊΌλ΄κΈ°
now = q.popleft()
result.append(now)
# ν΄λΉ μμμ μ°κ²°λ λ
Έλλ€μ μ§μ
μ°¨μμμ 1 λΉΌκΈ°
for j in range(1, n + 1):
if graph[now][j]:
indegree[j] -= 1
# μλ‘κ² μ§μ
μ°¨μκ° 0μ΄ λλ λ
Έλλ₯Ό νμ μ½μ
if indegree[j] == 0:
q.append(j)
# μ¬μ΄ν΄μ΄ λ°μνλ κ²½μ°(μΌκ΄μ±μ΄ μλ κ²½μ°)
if cycle:
print("IMPOSSIBLE")
# μμ μ λ ¬ κ²°κ³Όκ° μ¬λ¬ κ°μΈ κ²½μ°
elif not certain:
print("?")
# μμ μ λ ¬μ μνν κ²°κ³Ό μΆλ ₯
else:
for i in result:
print(i, end=' ')
print()