문제.

풀이.
https://turret1234.tistory.com/182
백준 4386 별자리 만들기 - 파이썬
문제. 풀이. 크루스칼 알고리즘을 이용해서 풀었다. https://turret1234.tistory.com/181 백준 1197 최소 스패닝 트리 - 파이썬 문제. 풀이. 크루스칼 알고리즘 이용하여 풀었다. https://ko.wikipedia.org/wiki/..
turret1234.tistory.com
풀이랑 거의 똑같은데
이미 이어져있는 점의 입력이 들어올때 미리 union 연산을 해주면 된다.
소스코드.
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(): | |
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, m = map(int, input().split()) | |
point = [] | |
old_point = [] | |
parent = [i for i in range(n)] | |
graph =[] | |
for i in range(n): | |
x, y = map(int, input().split()) | |
point.append([x, y]) | |
# 이미 연결된 점은 미리 union | |
for i in range(m): | |
x, y = map(int, input().split()) | |
union(x-1, y-1) | |
# 그래프 만들기 | |
for i in range(len(point)): | |
for j in range(i+1, len(point)): | |
graph.append([i, j, distance(point[i], point[j])]) | |
graph.sort(key = lambda x: x[2]) | |
print('%.2f' %(kruskal())) |
'프로그래밍 > 백준' 카테고리의 다른 글
백준 15681 트리와 쿼리 - 파이썬 (0) | 2021.08.04 |
---|---|
백준 2887 행성 터널 - 파이썬 (0) | 2021.08.04 |
백준 4386 별자리 만들기 - 파이썬 (0) | 2021.08.04 |
백준 1197 최소 스패닝 트리 - 파이썬 (0) | 2021.08.04 |
백준 9372 상근이의 여행 - 파이썬 (0) | 2021.08.04 |