HTD
[Python] 백준 4386번: 별자리 만들기 본문
https://www.acmicpc.net/problem/4386
4386번: 별자리 만들기
도현이는 우주의 신이다. 이제 도현이는 아무렇게나 널브러져 있는 n개의 별들을 이어서 별자리를 하나 만들 것이다. 별자리의 조건은 다음과 같다. 별자리를 이루는 선은 서로 다른 두 별을 일
www.acmicpc.net
import sys
import math
import itertools
input = sys.stdin.readline
def getDistance(p1, p2):
return math.sqrt(((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2))
def find(x):
if parent[x] == x:
return x
px = find(parent[x])
parent[x] = px
return px
def union(x, y):
px, py = find(x), find(y)
if px > py:
parent[px] = py
else:
parent[py] = px
if __name__ == '__main__':
# 입력
N = int(input())
stars = [list(map(float, input().split())) for _ in range(N)]
# For union-find
parent = [i for i in range(N)]
# For kruskal
sets = []
for i1, i2 in itertools.combinations(parent, 2):
sets.append([i1, i2, getDistance(stars[i1], stars[i2])])
# 거리에 대해 오름차순 정렬
sets.sort(key=lambda x: x[2])
# Kruskal
minCost = 0
for i1, i2, d in sets:
if find(i1) != find(i2):
union(i1, i2)
minCost += d
# 출력
print("{:.2f}".format(minCost))
Kruskal 알고리즘을 사용하면 된다. 기존 크루스칼에서 어떠한 변형이 없으므로 자세한 설명은 아래 링크로 대체한다.
[Python] 백준 1197번: 최소 스패닝 트리
https://www.acmicpc.net/problem/1197 import sys input = sys.stdin.readline def find(x): if parents[x] == x: return x parents[x] = find(parents[x]) return parents[x] def union(x, y): x, y = find(x),..
rccode.tistory.com
'Algorithm > 백준' 카테고리의 다른 글
[Python] 백준 1520번: 내리막 길 (0) | 2021.08.16 |
---|---|
[Python] 백준 1509번: 팰린드롬 분할 (0) | 2021.08.15 |
[Python] 백준 1007번: 벡터 매칭 (0) | 2021.08.11 |
[Python] 백준 1507번: 궁금한 민호 (0) | 2021.08.10 |
[Python] 백준 9345번: 디지털 비디오 디스크(DVDs) (0) | 2021.08.09 |