https://www.acmicpc.net/problem/15686
N, M = map(int, input().split())
arr = [list(map(int, input().split())) for _ in range(N)]
chicken = []
def calc_distance(x, y):
min = 999
min_chicken = 0
for c in chicken:
dist = abs(x - c[0]) + abs(y - c[1])
if dist < min:
min = dist
min_chicken = c
min_chicken[2] += 1
return min
for i in range(N):
for j in range(N):
if arr[i][j] == 2:
chicken.append([i, j, 0])
res = 0
for i in range(N):
for j in range(N):
if arr[i][j] == 1:
calc_distance(i, j);
chicken = sorted(chicken, key=lambda x: x[2])
while len(chicken) > M:
if chicken[0][2] == chicken[-1][2] and len(chicken) > M + 1:
chicken.pop(0)
chicken.pop(-1)
else:
chicken.pop(0)
for i in range(N):
for j in range(N):
if arr[i][j] == 1:
res += calc_distance(i, j);
print(res)
..........
(정답 슬쩍)
from itertools import combinations
N, M = map(int, input().split())
city = [list(map(int, input().split())) for _ in range(N)]
houses = []
chickens = []
for i in range(N):
for j in range(N):
if city[i][j] == 1:
houses.append([i, j])
elif city[i][j] == 2:
chickens.append([i, j])
min_city_chicken_distance = float('inf')
for chicken_comb in combinations(chickens, M):
city_chicken_distance = 0
for hx, hy in houses:
chicken_distance = min(abs(hx-cx)+abs(hy-cy) for cx, cy in chicken_comb)
city_chicken_distance += chicken_distance
if city_chicken_distance < min_city_chicken_distance:
min_city_chicken_distance = city_chicken_distance
print(min_city_chicken_distance)