๐๏ธ 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์ ์ฌ์ฉํ ์๊ฐ์ ํ์ง๋ ๋ชปํ๋ค.
์ถ์ฒ