๋ฌธ์
๋ฐฑ์ค ์จ๋ผ์ธ ์ ์ง - 1197๋ฒ
ํ์ด ๊ณผ์
์ต์ ์คํจ๋ ํธ๋ฆฌ
๋ฅผ ๊ตฌํ๋ ๋ฌธ์ ์
๋๋ค.
๊ธฐ๋ณธ ๋ฌธ์ ์ด๊ธฐ ๋๋ฌธ์ ๋ณ๋๋ก ๋ณต์กํ ๋ก์ง์ด ์ถ๊ฐ๋์ง๋ ์์์ต๋๋ค.
์ค๋๋ง์ MST
๋ฌธ์ ๋ฅผ ํ๋ฒ ํ์ด๋ณด๊ณ ์ถ์ด์ ๊ฐ์ฅ ๊ธฐ๋ณธ์ด ๋๋ ๋ฌธ์ ๋ฅผ ํ๋ฒ ํ์ด๋ดค์ต๋๋ค. ๐
์ฝ๋
import sys
def union(u, v):
pu, pv = find(u), find(v)
if pu != pv:
if rank[pu] > rank[pv]:
parent[pv] = pu
else:
parent[pu] = pv
if rank[pu] == rank[pv]:
rank[pv] += 1
def find(u):
if parent[u] == u:
return u
parent[u] = find(parent[u])
return parent[u]
def solution():
acc = 0
edges.sort(key=lambda edge: edge[2])
for frm, to, weight in edges:
if find(frm) != find(to):
union(frm, to)
acc += weight
return acc
if __name__ == '__main__':
V, E = list(map(int, sys.stdin.readline().split()))
edges = [list(map(int, sys.stdin.readline().split())) for _ in range(E)]
parent = [i for i in range(V + 1)]
rank = [0 for _ in range(V + 1)]
answer = solution()
print(answer)
๋ฐ์ํ
'๐ algorithm > boj' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
BOJ 13700 - ์์ ๋ฒ์ฃ (0) | 2021.06.29 |
---|---|
BOJ 14950 - ์ ๋ณต์ (0) | 2021.06.25 |
BOJ 4963 - ์ฌ์ ๊ฐ์ (0) | 2021.06.15 |
BOJ 5568 - ์นด๋ ๋๊ธฐ (0) | 2021.06.14 |
BOJ 5972 - ํ๋ฐฐ ๋ฐฐ์ก (0) | 2021.06.10 |
๐ฌ ๋๊ธ