forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path8.py
More file actions
48 lines (40 loc) Β· 1.47 KB
/
8.py
File metadata and controls
48 lines (40 loc) Β· 1.47 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
48
# νΉμ μμκ° μν μ§ν©μ μ°ΎκΈ°
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()
last = 0 # μ΅μ μ μ₯ νΈλ¦¬μ ν¬ν¨λλ κ°μ μ€μμ κ°μ₯ λΉμ©μ΄ ν° κ°μ
# κ°μ μ νλμ© νμΈνλ©°
for edge in edges:
cost, a, b = edge
# μ¬μ΄ν΄μ΄ λ°μνμ§ μλ κ²½μ°μλ§ μ§ν©μ ν¬ν¨
if find_parent(parent, a) != find_parent(parent, b):
union_parent(parent, a, b)
result += cost
last = cost
print(result - last)