Algorithm(CodeTree, Python)/Backtracking
[코드트리] 2n개 중에 n개의 숫자를 적절하게 고르기 Python
by kurooru
2023. 2. 3.
# n, m 입력
n, m = map(int, input().split())
# points
points = [
tuple(map(int, input().split()))
for _ in range(n)
]
# calc(curr_comb)
def calc(curr_comb):
# max_dist
max_dist = 0
for i in range(m-1):
for j in range(i+1, m):
# x1, y1, x2, y2 unpacking
x1, y1 = curr_comb[i]
x2, y2 = curr_comb[j]
# curr_dist
curr_dist = (x1 - x2) ** 2 + (y1 - y2) ** 2
# max_dist update
max_dist = max(max_dist, curr_dist)
# 반환
return max_dist
# make_comb(curr_idx, cnt)
def make_comb(curr_idx, cnt):
# 전역 변수 선언
global min_dist
# 종료조건
if curr_idx == n:
if cnt == m:
# min_dist update
min_dist = min(min_dist, calc(comb))
return
comb.append(points[curr_idx])
make_comb(curr_idx+1, cnt+1)
comb.pop()
make_comb(curr_idx+1, cnt)
# 설계
# min_dist
import sys
min_dist = sys.maxsize
# 조합 만들기
# comb
comb = []
make_comb(0, 0)
# 출력
print(min_dist)