문제.

풀이.
크루스칼 알고리즘 이용하여 풀었다.
크러스컬 알고리즘 - 위키백과, 우리 모두의 백과사전
컴퓨터 과학에서, 크러스컬 알고리즘(영어: Kruskal’s algorithm)은 최소 비용 신장 부분 트리를 찾는 알고리즘이다. 변의 개수를 E {\displaystyle E} , 꼭짓점의 개수를 V {\displaystyle V} 라고 하면 이 알고
ko.wikipedia.org
소스코드.
This file contains hidden or 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 | |
V, E = map(int, input().split()) | |
graph = [] | |
parent = [i for i in range(V+1)] | |
for i in range(E): | |
u, v, w = map(int, input().split()) | |
graph.append([u, v, w]) | |
graph.sort(key = lambda x: x[2]) | |
print(kruskal()) |
'프로그래밍 > 백준' 카테고리의 다른 글
백준 1774 우주신과의 교감 - 파이썬 (0) | 2021.08.04 |
---|---|
백준 4386 별자리 만들기 - 파이썬 (0) | 2021.08.04 |
백준 9372 상근이의 여행 - 파이썬 (0) | 2021.08.04 |
백준 20040 사이클 게임 - 파이썬 (0) | 2021.08.04 |
백준 4195 친구 네트워크 - 파이썬 (0) | 2021.08.03 |