
풀이.
최소 신장 트리 알고리즘인 크루스칼 알고리즘을 이용해서 풀면된다.
최소 비용을 구해야하는 문제이니 cost를 기준으로 graph를 정렬 시킨 후
크루스칼 알고리즘을 이용하면 어렵지 않게 풀 수 있다.
최소 신장 트리 알고리즘이 가물가물해서 한번 풀어봤다.
소스코드.
<script src="https://gist.github.com/hanhyung6376/f6622fd34ba8c968bc12afce179c4d80.js"></script>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
def union(a, b): | |
a = find(a) | |
b = find(b) | |
if a < b: | |
parent[b] = a | |
else: | |
parent[a] = b | |
def find(target): | |
if target == parent[target]: | |
return target | |
parent[target] = find(parent[target]) | |
return parent[target] | |
def kruskal(): | |
cost = 0 | |
for u, v, w in graph: | |
if find(u) != find(v): | |
union(u, v) | |
cost += w | |
return cost | |
input = sys.stdin.readline | |
n = int(input()) | |
m = int(input()) | |
graph = [] | |
parent = [i for i in range(n+1)] | |
for i in range(m): | |
u, v, w = map(int, input().split()) | |
graph.append([u, v, w]) | |
graph.sort(key = lambda x: x[2]) | |
print(kruskal()) |
'프로그래밍 > 백준' 카테고리의 다른 글
[백준] 11724. 연결 요소의 개수 - 파이썬 (0) | 2021.10.09 |
---|---|
[백준] 17435. 합성함수와 쿼리 (0) | 2021.10.05 |
[백준] 18352. 특정 거리의 도시 찾기 - 파이썬 (0) | 2021.09.27 |
[백준] 16975. 수열과 쿼리 21 - 파이썬 (0) | 2021.09.25 |
[백준] 1238. 파티 - 파이썬 (0) | 2021.09.24 |