1774번: 우주신과의 교감
(1,1) (3,1) (2,3) (4,3) 이렇게 우주신들과 황선자씨의 좌표가 주어졌고 1번하고 4번이 연결되어 있다. 그렇다면 1번하고 2번을 잇는 통로를 만들고 3번하고 4번을 잇는 통로를 만들면 신들과 선자씨끼
www.acmicpc.net
import math
def find(i):
if parent[i] != i:
parent[i] = find(parent[i])
return parent[i]
def union(i, j):
i = find(i)
j = find(j)
if i != j:
parent[i] = j
N, M = map(int, input().split())
loc = [(0, 0)] + [tuple(map(int, input().split())) for _ in range(N)]
edges = []
for i in range(1, N+1):
for j in range(i+1, N+1):
x1, y1 = loc[i]
x2, y2 = loc[j]
w = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
edges.append((w, i, j))
edges.sort()
parent = [i for i in range(N+1)]
# 이미 연결된 간선 전처리
for _ in range(M):
n1, n2 = map(int, input().split())
union(n1, n2)
# MST 간선 찾기
l = 0
for w, n1, n2 in edges:
if find(n1) != find(n2):
union(n1, n2)
l += w
print(f"{l:0.2f}")
'BOJ 알고리즘 (패캠) > 그래프' 카테고리의 다른 글
5719번: 거의최단경로 (그래프, 다익스트라) - Fastcampus (0) | 2020.10.22 |
---|---|
10282번: 해킹 (그래프, 다익스트라) - Fastcampus (0) | 2020.10.22 |
1325번: 효율적인해킹 (그래프, BFS, DFS) - Fastcampus (0) | 2020.10.21 |
1012번: 유기농배추 (그래프, BFS, DFS) - Fastcampus (0) | 2020.10.16 |
2606번: 바이러스 (그래프, BFS, DFS) - Fastcampus (0) | 2020.10.15 |