Post

[BOJ] 15686. ์น˜ํ‚จ๋ฐฐ๋‹ฌ(python)

๐Ÿ“Œ๋ฌธ์ œ

Alt text

๐Ÿ’ช์•„์ด๋””์–ด

  1. m๊ฐœ ์น˜ํ‚จ์ง‘ ๊ณ ๋ฅด๊ธฐ
    ์ˆœ์„œ์™€ ์ค‘๋ณต์ด ์—†๋Š” combination์„ ํ†ตํ•ด ์ „์ฒด ์น˜ํ‚จ์ง‘ ์ค‘ m๊ฐœ์˜ ์น˜ํ‚จ์ง‘์„ ๊ณ ๋ฅธ๋‹ค.

  2. ์น˜ํ‚จ ๊ฑฐ๋ฆฌ ๊ตฌํ•˜๊ธฐ
    ๊ฐ ์ง‘๋งˆ๋‹ค ๊ณ ๋ฅธ m๊ฐœ์˜ ์น˜ํ‚จ์ง‘์—์„œ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ์น˜ํ‚จ์ง‘๊ณผ์˜ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•œ๋‹ค.

  3. ๋„์‹œ์˜ ์น˜ํ‚จ ๊ฑฐ๋ฆฌ ๊ตฌํ•˜๊ธฐ

๐Ÿฅ‚์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import sys; input = sys.stdin.readline
from itertools import combinations

def chickenRoad(house, chicken):
    hx, hy = house
    cx, cy = chicken
    return abs(hx-cx) + abs(hy-cy)

houses = []
chickenShops = []

n, m = map(int, input().split())
for i in range(n):
    town = input().split()
    for j in range(n):
        if town[j] == '1': houses.append((i+1,j+1))
        elif town[j] == '2': chickenShops.append((i+1,j+1))

answer = float('inf')
for c in combinations(chickenShops,m):
    combiRoad = 0
    for h in houses:
        streetPerHouse = float('inf')
        for i in range(m):
            streetPerHouse = min(streetPerHouse, chickenRoad(h,c[i]))
        combiRoad += streetPerHouse
    answer = min(answer,combiRoad)
print(answer)
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.