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
48 lines (40 loc) ยท 1.4 KB
/
3.py
File metadata and controls
48 lines (40 loc) ยท 1.4 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
# ๋
ธ๋์ ๊ฐ์์ ๊ฐ์ ์ ๊ฐ์ ์
๋ ฅ๋ฐ๊ธฐ
n, m = map(int, input().split())
parent = [0] * (n + 1) # ๋ถ๋ชจ ํ
์ด๋ธ ์ด๊ธฐํ
# ๋ชจ๋ ๊ฐ์ ์ ๋ด์ ๋ฆฌ์คํธ์, ์ต์ข
๋น์ฉ์ ๋ด์ ๋ณ์
edges = []
result = 0
# ๋ถ๋ชจ ํ
์ด๋ธ์์์, ๋ถ๋ชจ๋ฅผ ์๊ธฐ ์์ ์ผ๋ก ์ด๊ธฐํ
for i in range(1, n + 1):
parent[i] = i
# ๋ชจ๋ ๊ฐ์ ์ ๋ํ ์ ๋ณด๋ฅผ ์
๋ ฅ๋ฐ๊ธฐ
for _ in range(m):
x, y, z = map(int, input().split())
# ๋น์ฉ์์ผ๋ก ์ ๋ ฌํ๊ธฐ ์ํด์ ํํ์ ์ฒซ ๋ฒ์งธ ์์๋ฅผ ๋น์ฉ์ผ๋ก ์ค์
edges.append((z, x, y))
# ๊ฐ์ ์ ๋น์ฉ์์ผ๋ก ์ ๋ ฌ
edges.sort()
total = 0 # ์ ์ฒด ๊ฐ๋ก๋ฑ ๋น์ฉ
# ๊ฐ์ ์ ํ๋์ฉ ํ์ธํ๋ฉฐ
for edge in edges:
cost, a, b = edge
total += cost
# ์ฌ์ดํด์ด ๋ฐ์ํ์ง ์๋ ๊ฒฝ์ฐ์๋ง ์งํฉ์ ํฌํจ
if find_parent(parent, a) != find_parent(parent, b):
union_parent(parent, a, b)
result += cost
print(total - result)