๋ฌธ์
๋ฐฑ์ค ์จ๋ผ์ธ ์ ์ง - 1922๋ฒ
ํ์ด ๊ณผ์
๋ชจ๋ ์ปดํจํฐ๋ฅผ ์ฐ๊ฒฐํ๋ ๋คํธ์ํฌ๋ฅผ ๊ตฌ์ฑํ๋ ์ต์ ๋น์ฉ์ ๊ตฌํ๋ ๋ฌธ์ ์
๋๋ค.ํฌ๋ฃจ์ค์นผ ์๊ณ ๋ฆฌ์ฆ
์ ์ด์ฉํด์ MST
๋ฅผ ๊ตฌํํ์ผ๋ฉฐ union
์ฐ์ฐ์์๋ ๋ญํฌ ์ต์ ํ์ ๊ฒฝ๋ก ์์ถ์ ์ฌ์ฉํ์ต๋๋ค.
์ฝ๋
import sys
def union(v1, v2):
r1, r2 = find(v1), find(v2)
if r1 == r2:
return
if rank[r1] > rank[r2]:
parent[r2] = r1
else:
parent[r1] = r2
if rank[r1] == rank[r2]:
rank[r2] += 1
def find(v):
if parent[v] != v:
parent[v] = find(parent[v])
return parent[v]
def kruskal():
total_cost = 0
for v in range(1, N + 1):
parent[v] = v
rank[v] = 0
for frm, to, cost in sorted(edges, key=lambda edge: edge[2]):
r1, r2 = find(frm), find(to)
if r1 != r2:
union(r1, r2)
total_cost += cost
return total_cost
def solution():
answer = kruskal()
return answer
if __name__ == '__main__':
N = int(input())
M = int(input())
edges = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]
parent = [-1] * (N + 1)
rank = [0] * (N + 1)
answer = solution()
print(answer)
๋ฐ์ํ
'๐ algorithm > boj' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
BOJ 14940 - ์ฌ์ด ์ต๋จ๊ฑฐ๋ฆฌ (0) | 2021.04.13 |
---|---|
BOJ 16441 - ์๊ธฐ๋ผ์ง์ ๋๋ (0) | 2021.04.13 |
BOJ 20006 - ๋ญํน์ ๋๊ธฐ์ด (0) | 2021.04.13 |
BOJ 2869 - ๋ฌํฝ์ด๋ ์ฌ๋ผ๊ฐ๊ณ ์ถ๋ค (0) | 2021.04.13 |
BOJ 16926 - ๋ฐฐ์ด ๋๋ฆฌ๊ธฐ 1 (0) | 2021.04.13 |
๐ฌ ๋๊ธ