forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path3.py
More file actions
40 lines (33 loc) ยท 1.13 KB
/
3.py
File metadata and controls
40 lines (33 loc) ยท 1.13 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
# ํน์ ์์๊ฐ ์ํ ์งํฉ์ ์ฐพ๊ธฐ
def find_parent(parent, x):
# ๋ฃจํธ ๋
ธ๋๊ฐ ์๋๋ผ๋ฉด, ๋ฃจํธ ๋
ธ๋๋ฅผ ์ฐพ์ ๋๊น์ง ์ฌ๊ท์ ์ผ๋ก ํธ์ถ
if parent[x] != x:
parent[x] = find_parent(parent, parent[x])
return parent[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=' ')