티스토리 뷰

www.acmicpc.net/problem/4386

 

4386번: 별자리 만들기

도현이는 우주의 신이다. 이제 도현이는 아무렇게나 널브러져 있는 n개의 별들을 이어서 별자리를 하나 만들 것이다. 별자리의 조건은 다음과 같다. 별자리를 이루는 선은 서로 다른 두 별을 일�

www.acmicpc.net

 

import sys
import math

INF = float(1e9)

n = int(sys.stdin.readline().rstrip())
edges = []
coordinates = []
parent = [i for i in range(n)]

for _ in range(n):
    x, y = map(float, sys.stdin.readline().rstrip().split())
    coordinates.append((x, y))

for i in range(n - 1):
    x1, y1 = coordinates[i]
    for j in range(i + 1, n):
        x2, y2 = coordinates[j]
        edges.append((round(math.dist((x1, y1), (x2, y2)), 2), i, j))

edges.sort()


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


def union_parent(parent, a, b):
    a = find_parent(parent, a)
    b = find_parent(parent, b)

    if a < b:
        parent[b] = a
    else:
        parent[a] = b


result = 0

for edge in edges:
    cost, c1, c2 = edge

    if find_parent(parent, c1) != find_parent(parent, c2):
        union_parent(parent, c1, c2)
        result += cost

print(result)
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
글 보관함