[백준] 1774번 우주신과의 교감

JaeYeop·2022년 5월 10일
0

백준

목록 보기
19/19

[문제]

https://www.acmicpc.net/problem/1774

[코드]

import sys
input = sys.stdin.readline

def find_parent(parent, x):
    if parent[x] != x:
        parent[x] = find_parent(parent, parent[x])
    return parent[x]

def union_parent(parent, x, y):
    a = find_parent(parent, x)
    b = find_parent(parent, y)
    if a < b:
        parent[b] = a
    else:
        parent[a] = b

n, m = map(int, input().split())
location = []
for i in range(n):
    x, y = map(int, input().split())
    location.append([x, y, i])
parent = [i for i in range(n)]
for i in range(m):
    x, y = map(int, input().split())
    union_parent(parent, x - 1, y - 1)
graph = []
for i in range(n):
    for j in range(i + 1, n):
        graph.append([((location[j][0] - location[i][0]) ** 2 + (location[j][1] - location[i][1]) ** 2) ** (1 / 2), i, j])

graph.sort()
result = []
for i in graph:
    if find_parent(parent, i[1]) != find_parent(parent, i[2]):
        union_parent(parent, i[1], i[2])
        result.append(i[0])

print(format(sum(result), ".2f"))

[풀이]

이 문제는 이미 연결된 간선들을 제외하고, 새로 이어줄 간선의 최소 비용만 구하면 된다

그래서 이미 연결된 간선을 입력받고 그 간선을 union_parent 해준 다음에 최소 신장 트리 알고리즘을 이용해 구하자

profile
이게 왜 틀리지... (나의 메모용 블로그)

0개의 댓글