forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1.py
40 lines (33 loc) Β· 1.12 KB
/
1.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
# νΉμ μμκ° μν μ§ν©μ μ°ΎκΈ°
def find_parent(parent, x):
# λ£¨νΈ λ
Έλκ° μλλΌλ©΄, λ£¨νΈ λ
Έλλ₯Ό μ°Ύμ λκΉμ§ μ¬κ·μ μΌλ‘ νΈμΆ
if parent[x] != x:
return find_parent(parent, parent[x])
return x
# λ μμκ° μν μ§ν©μ ν©μΉκΈ°
def union_parent(parent, a, b):
a = find_parent(parent, a)
b = find_parent(parent, b)
if a < b:
parent[b] = a
else:
parent[a] = b
# λ
Έλμ κ°μμ κ°μ (Union μ°μ°)μ κ°μ μ
λ ₯ λ°κΈ°
v, e = map(int, input().split())
parent = [0] * (v + 1) # λΆλͺ¨ ν
μ΄λΈ μ΄κΈ°ννκΈ°
# λΆλͺ¨ ν
μ΄λΈμμμ, λΆλͺ¨λ₯Ό μκΈ° μμ μΌλ‘ μ΄κΈ°ν
for i in range(1, v + 1):
parent[i] = i
# Union μ°μ°μ κ°κ° μν
for i in range(e):
a, b = map(int, input().split())
union_parent(parent, a, b)
# κ° μμκ° μν μ§ν© μΆλ ₯νκΈ°
print('κ° μμκ° μν μ§ν©: ', end='')
for i in range(1, v + 1):
print(find_parent(parent, i), end=' ')
print()
# λΆλͺ¨ ν
μ΄λΈ λ΄μ© μΆλ ₯νκΈ°
print('λΆλͺ¨ ν
μ΄λΈ: ', end='')
for i in range(1, v + 1):
print(parent[i], end=' ')