반응형
https://www.acmicpc.net/problem/15686
15686번: 치킨 배달
크기가 N×N인 도시가 있다. 도시는 1×1크기의 칸으로 나누어져 있다. 도시의 각 칸은 빈 칸, 치킨집, 집 중 하나이다. 도시의 칸은 (r, c)와 같은 형태로 나타내고, r행 c열 또는 위에서부터 r번째 칸, 왼쪽에서부터 c번째 칸을 의미한다. r과 c는 1부터 시작한다. 이 도시에 사는 사람들은 치킨을 매우 좋아한다. 따라서, 사람들은 "치킨 거리"라는 말을 주로 사용한다. 치킨 거리는 집과 가장 가까운 치킨집 사이의 거리이다. 즉, 치킨 거리는
www.acmicpc.net


삼성SW역량테스트 기출문제. Brute Force + BFS 형태.
치킨집 중에 M개를 고르는 형태는 '연구소 3' 문제와 마찬가지로 combinations 라이브러리를 써서 해결할 수 있다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import math | |
from itertools import combinations | |
n, m = map(int, sys.stdin.readline().split()) | |
# 치킨집 위치, 집 위치 | |
chicken, house = [], [] | |
# 치킨집 위치 / 집 위치 저장 | |
for y in range(n): | |
tmp = list(map(int, sys.stdin.readline().split())) | |
for x in range(len(tmp)): | |
if tmp[x] == 1: | |
house.append((y,x)) | |
elif tmp[x] == 2: | |
chicken.append((y,x)) | |
# 치킨집 중 m개의 치킨집을 선택하는 경우의 수 | |
candidate = list(combinations(chicken, m)) | |
# 거리 최소값 구하기. | |
# 각 집 위치마다 모든 치킨집과의 거리를 구하고, 최솟값만 result에 더한다. | |
def get_min_distance(candidate, house): | |
result = 0 | |
for hy, hx in house: | |
tmp_min = math.inf | |
for y, x in candidate: | |
if abs(hy-y) + abs(hx-x) < tmp_min: | |
tmp_min = abs(hy-y)+ abs(hx-x) | |
result += tmp_min | |
return result | |
# 거리의 최솟값 | |
min_result = math.inf | |
for i in candidate: | |
result = get_min_distance(list(i),house) | |
if min_result > result: | |
min_result = result | |
print(min_result) |
반응형
'프로그래밍 > 코딩테스트 문제풀이' 카테고리의 다른 글
[Python] 프로그래머스. 게임 맵 최단거리 (Level 4) (0) | 2019.11.04 |
---|---|
[Python] 백준 14502. 연구소 (0) | 2019.11.03 |
[Python] 프로그래머스. 배달 (Level 3) (0) | 2019.11.01 |
[Python] 프로그래머스. 짝지어 제거하기 (Level 3) (0) | 2019.10.31 |
[Python] 프로그래머스. 가장 먼 노드 (Level 3) (0) | 2019.10.30 |