728x90
https://www.acmicpc.net/problem/1647
최소 신장 트리를 구할 때 유니온-파인드(=크루스칼 알고리즘 구현) 방법을 이용해 구하는 문제이다.
언듯보면 까다롭지만, MST를 구한 후 "값이 가장 큰 간선을 하나 제거"하면 "최소 스패닝 트리 2개"가 생긴다는 발상이 키포인트이다
또한, 가장 가중치가 가장 작은 간선부터 보면서 트리를 구성하기 때문에 자연스레 MST가 생성된다 (=크루스칼,Kruskal)
N,M = map(int,input().split())
graph = []
for _ in range(M):
A,B,C = map(int, input().split())
graph.append([A,B,C])
graph.sort(key = lambda x:x[2])
#print(graph)
parent = [0] * (N+1)
for i in range(1, N + 1):
parent[i] = i
def find_parent(x):
if parent[x] != x:
parent[x] = find_parent(parent[x])
return parent[x]
def union(a, b):
a = find_parent(a)
b = find_parent(b)
if a < b:
parent[b] = a
else:
parent[a] = b
result, max_cost = 0,0
for edge in graph:
start, end, cost = edge
if find_parent(start) != find_parent(end): # 다른 그룹이면
union(start, end)
result += cost
max_cost = max(cost, max_cost)
print(result - max_cost)728x90
'알고리즘 > 백준(BOJ)' 카테고리의 다른 글
| [백준/파이썬] 16234번 인구 이동 (0) | 2026.01.20 |
|---|---|
| [백준/파이썬] 13549번 숨바꼭질 3 (0) | 2023.07.08 |
| [백준/파이썬] 1041번 주사위 (0) | 2023.05.31 |
| [백준/파이썬] 12919번 A와 B 2 (0) | 2023.05.27 |
| [백준/파이썬] 1111번 IQ Test (0) | 2023.05.26 |