forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path5.py
More file actions
46 lines (38 loc) ยท 1.37 KB
/
5.py
File metadata and controls
46 lines (38 loc) ยท 1.37 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
# ํน์ ์์๊ฐ ์ํ ์งํฉ์ ์ฐพ๊ธฐ
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) # ๋ถ๋ชจ ํ
์ด๋ธ ์ด๊ธฐํํ๊ธฐ
# ๋ชจ๋ ๊ฐ์ ์ ๋ด์ ๋ฆฌ์คํธ์, ์ต์ข
๋น์ฉ์ ๋ด์ ๋ณ์
edges = []
result = 0
# ๋ถ๋ชจ ํ
์ด๋ธ์์์, ๋ถ๋ชจ๋ฅผ ์๊ธฐ ์์ ์ผ๋ก ์ด๊ธฐํ
for i in range(1, v + 1):
parent[i] = i
# ๋ชจ๋ ๊ฐ์ ์ ๋ํ ์ ๋ณด๋ฅผ ์
๋ ฅ ๋ฐ๊ธฐ
for _ in range(e):
a, b, cost = map(int, input().split())
# ๋น์ฉ์์ผ๋ก ์ ๋ ฌํ๊ธฐ ์ํด์ ํํ์ ์ฒซ ๋ฒ์งธ ์์๋ฅผ ๋น์ฉ์ผ๋ก ์ค์
edges.append((cost, a, b))
# ๊ฐ์ ์ ๋น์ฉ์์ผ๋ก ์ ๋ ฌ
edges.sort()
# ๊ฐ์ ์ ํ๋์ฉ ํ์ธํ๋ฉฐ
for edge in edges:
cost, a, b = edge
# ์ฌ์ดํด์ด ๋ฐ์ํ์ง ์๋ ๊ฒฝ์ฐ์๋ง ์งํฉ์ ํฌํจ
if find_parent(parent, a) != find_parent(parent, b):
union_parent(parent, a, b)
result += cost
print(result)