프로그래밍/백준
백준 4386 별자리 만들기 - 파이썬
터렛짓는다
2021. 8. 4. 11:42
문제.

풀이.
크루스칼 알고리즘을 이용해서 풀었다.
https://turret1234.tistory.com/181
백준 1197 최소 스패닝 트리 - 파이썬
문제. 풀이. 크루스칼 알고리즘 이용하여 풀었다. https://ko.wikipedia.org/wiki/%ED%81%AC%EB%9F%AC%EC%8A%A4%EC%BB%AC_%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98 크러스컬 알고리즘 - 위키백과, 우리 모두의 백과..
turret1234.tistory.com
랑 거의 유사한 문제이다.
입력 값 대로 거리를 계산해서 그래프를 만드는 부분을 제외하면 똑같다.
소스코드.
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 | |
import math | |
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 distance(a, b): | |
return math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2) | |
# 크루스칼 알고리즘 | |
def kruskal(): | |
tree_edges = 0 | |
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()) | |
point = [] | |
for i in range(n): | |
x, y= map(float, input().split()) | |
point.append([x, y]) | |
graph = [] | |
for i in range(len(point)): | |
for j in range(i+1, len(point)): | |
graph.append([i, j, distance(point[i], point[j])]) | |
parent = [i for i in range(len(graph))] | |
graph.sort(key = lambda x: x[2]) | |
print(round(kruskal(), 2)) |