Python/구현

[백준][Python] 15686번 : 치킨 배달

Mr_Chu 2020. 9. 9. 16:13

from itertools import combinations
import math
import sys

n,m = map(int, sys.stdin.readline().split())

# 각 집 위치마다 모든 치킨집 거리 계산 후 최소값 반환
def get_distance(select, home):
    answer = 0
    for hx, hy in home:
        ans_min = math.inf #무한값 넣기
        for x, y in select:
            if abs(hx-x)+abs(hy-y) < ans_min:
                ans_min = abs(hx-x)+abs(hy-y)
        answer += ans_min
    return answer
    
home, chi = [], []
# 집 위치, 치킨집 위치
for i in range(n):
    alist = list(map(int,sys.stdin.readline().split()))
    for j in range(len(alist)):
        if alist[j] == 1:
            home.append((i,j))
        elif alist[j] == 2:
            chi.append((i, j))

select = list(combinations(chi,m))

# 거리의 최솟값
res_min = math.inf
for i in select:
    result = get_distance(list(i),home)
    if res_min > result:
        res_min = result

print(res_min)

꺠달은 점:  sys.stdin.readline().split() 은 input().split()보다 빠르다