๐Ÿ—๏ธ Algorithm/๐ŸŸฉ ๋ฐฑ์ค€

๐ŸŸฉ [๋ฐฑ์ค€] [Python] [๊ตฌํ˜„] 15686๋ฒˆ_์น˜ํ‚จ ๋ฐฐ๋‹ฌ

Dbswnstjd 2022. 11. 22. 06:55

๋ฌธ์ œ

https://www.acmicpc.net/problem/15686

 

15686๋ฒˆ: ์น˜ํ‚จ ๋ฐฐ๋‹ฌ

ํฌ๊ธฐ๊ฐ€ N×N์ธ ๋„์‹œ๊ฐ€ ์žˆ๋‹ค. ๋„์‹œ๋Š” 1×1ํฌ๊ธฐ์˜ ์นธ์œผ๋กœ ๋‚˜๋ˆ„์–ด์ ธ ์žˆ๋‹ค. ๋„์‹œ์˜ ๊ฐ ์นธ์€ ๋นˆ ์นธ, ์น˜ํ‚จ์ง‘, ์ง‘ ์ค‘ ํ•˜๋‚˜์ด๋‹ค. ๋„์‹œ์˜ ์นธ์€ (r, c)์™€ ๊ฐ™์€ ํ˜•ํƒœ๋กœ ๋‚˜ํƒ€๋‚ด๊ณ , rํ–‰ c์—ด ๋˜๋Š” ์œ„์—์„œ๋ถ€ํ„ฐ r๋ฒˆ์งธ ์นธ

www.acmicpc.net

ํ’€์ด

# ๋ฐฑ์ค€ 15686๋ฒˆ ๋ฌธ์ œ - ์น˜ํ‚จ ๋ฐฐ๋‹ฌ
import sys
from itertools import combinations

input = sys.stdin.readline

n, m = map(int, input().split())
graph = list(list(map(int, input().split())) for _ in range(n))
result = 999999
house = []      # ์ง‘์˜ ์ขŒํ‘œ
chick = []      # ์น˜ํ‚จ์ง‘์˜ ์ขŒํ‘œ

for i in range(n):
    for j in range(n):
        if graph[i][j] == 1:
            house.append([i, j])
        elif graph[i][j] == 2:
            chick.append([i, j])

for chi in combinations(chick, m):  # m๊ฐœ์˜ ์น˜ํ‚จ์ง‘ ์„ ํƒ
    temp = 0            # ๋„์‹œ์˜ ์น˜ํ‚จ ๊ฑฐ๋ฆฌ
    for h in house: 
        chi_len = 999   # ๊ฐ ์ง‘๋งˆ๋‹ค ์น˜ํ‚จ ๊ฑฐ๋ฆฌ
        for j in range(m):
            chi_len = min(chi_len, abs(h[0] - chi[j][0]) + abs(h[1] - chi[j][1]))
        temp += chi_len
    result = min(result, temp)

print(result)

ํ’€๋‹ค๊ฐ€ ๋‹ต์€ ๋งž์•˜๋Š”๋ฐ ํ‹€๋ ธ๋‹ค๊ณ  ํ•ด์„œ ๋„์ €ํžˆ ์ƒ๊ฐ์ด ์•ˆ๋‚˜์„œ ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด๋ฅผ ๋ณด๊ณ  ํ•ด๊ฒฐํ•˜์˜€๋‹ค.

combination์„ ์‚ฌ์šฉํ•  ์ƒ๊ฐ์€ ํ•˜์ง€๋„ ๋ชปํ–ˆ๋‹ค. 

 

 

์ถœ์ฒ˜

https://codesyun.tistory.com/185