ํŒŒ์ด์ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ด์ฝ”ํ…Œ Ch12-13] ์น˜ํ‚จ ๋ฐฐ๋‹ฌ (๊ตฌํ˜„)

์€์ง„ 2022. 3. 15. 20:23

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ์„ค๋ช…

[์ด์ฝ”ํ…Œ Ch12-13] ์น˜ํ‚จ ๋ฐฐ๋‹ฌ (๊ตฌํ˜„)
์ด์ฝ”ํ…Œ

โœ๏ธIdea Sketch

๋ฌธ์ œ ์š”์•ฝ

์น˜ํ‚จ๊ฑฐ๋ฆฌ : ์ง‘๊ณผ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ์น˜ํ‚จ์ง‘๊ณผ์˜ ๊ฑฐ๋ฆฌ
๋„์‹œ์˜ ์น˜ํ‚จ๊ฑฐ๋ฆฌ : ์น˜ํ‚จ๊ฑฐ๋ฆฌ์˜ ํ•ฉ

์น˜ํ‚จ์ง‘ m๊ฐœ๋งŒ ๋‚จ๊ฒจ์•ผ ํ•จ
๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฐ€์žฅ ์ž‘์€ '๋„์‹œ์˜ ์น˜ํ‚จ๊ฑฐ๋ฆฌ'๋Š”?


์‹œ๊ฐ„๋ณต์žก๋„

์ฐธ๊ณ ์‚ฌ์ดํŠธ
์ด ๋ฌธ์ œ๋Š” n * n์˜ ๋ชจ๋“  ๊ทธ๋ž˜ํ”„ ์˜์—ญ์„ ํƒ์ƒ‰ ํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค. ์ง‘๊ณผ ์น˜ํ‚จ์ง‘๋งŒ ํƒ์ƒ‰ํ•˜๋ฉด ๋œ๋‹ค. ์ง‘์€ 2N๊ฐœ, ์ฆ‰ ์ตœ๋Œ€ 100๊ฐœ์ด๋ฉฐ, ์น˜ํ‚จ์ง‘ M์€ ์ตœ๋Œ€ 13์ด๋‹ค. ์ด๋Š” ์‹œ๊ฐ„ ์ดˆ๊ณผ๋ฅผ ์•”์‹œํ•˜๋Š” ์—ฐ์‚ฐํšŸ์ˆ˜ 1์–ต๊ณผ๋Š” ๊ฑฐ๋ฆฌ๊ฐ€ ๋ฉ€๋‹ค. ๋”ฐ๋ผ์„œ ๋ธŒ๋ฃจํŠธํฌ์Šค ์•Œ๊ณ ๋ฆฌ์ฆ˜(์™„์ „ ํƒ์ƒ‰)์„ ์‹œ๋„ํ•ด๋ด„์ง ํ•˜๋‹ค.

๊ทธ๋ฆฌ๊ณ  ์น˜ํ‚จ์ง‘ ์ตœ๋Œ€ 13๊ฐœ ์ค‘์—์„œ M๊ฐœ๋ฅผ ๊ณ ๋ฅด๋Š” ์กฐํ•ฉ์˜ ์ตœ๋Œ€ ๊ฒฝ์šฐ์˜ ์ˆ˜๋Š” 100,000์— ๊ฐ€๊น๋‹ค. (M์ด ์ค‘๊ฐ„๊ฐ’ 6, 7์ผ ๊ฒฝ์šฐ 100,000์— ๊ฐ€๊น๋‹ค. )


์•Œ๊ณ ๋ฆฌ์ฆ˜ : ๊ตฌํ˜„, ๋ธŒ๋ฃจํŠธํฌ์Šค (์™„์ „ ํƒ์ƒ‰)

  1. ์น˜ํ‚จ์ง‘ M๊ฐœ์˜ ์กฐํ•ฉ ๊ตฌํ•˜๊ธฐ
  2. ๋ชจ๋“  ์กฐํ•ฉ์— ๋Œ€ํ•œ ๋„์‹œ์˜ ์น˜ํ‚จ๊ฑฐ๋ฆฌ ๊ตฌํ•˜๊ธฐ


โœ๏ธ๋‚ด ์†Œ์Šค์ฝ”๋“œ

  1. ๋นˆ์นธ, ์น˜ํ‚จ์ง‘, ์ง‘ ๊ตฌ๋ถ„ํ•˜๊ธฐ
  2. ์น˜ํ‚จ์ง‘ M๊ฐœ์˜ ์กฐํ•ฉ ๊ตฌํ•˜๊ธฐ (combinations ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์‚ฌ์šฉ)
  3. ๋ชจ๋“  ์กฐํ•ฉ์— ๋Œ€ํ•œ ๋„์‹œ์˜ ์น˜ํ‚จ๊ฑฐ๋ฆฌ ๊ตฌํ•˜๊ธฐ
    • ์น˜ํ‚จ ๊ฑฐ๋ฆฌ cl : ์ง‘๊ณผ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ์น˜ํ‚จ์ง‘๊ณผ์˜ ๊ฑฐ๋ฆฌ์ด๋‹ค. ๋”ฐ๋ผ์„œ ์ง‘์œผ๋กœ๋ถ€ํ„ฐ ์น˜ํ‚จ์ง‘ ์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ๋ฅผ ๋ชจ๋‘ ๊ตฌํ•œ ํ›„, ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ ์ €์žฅํ•œ๋‹ค.
    • ๋„์‹œ์˜ ์น˜ํ‚จ ๊ฑฐ๋ฆฌ ccl : ์น˜ํ‚จ ๊ฑฐ๋ฆฌ์˜ ํ•ฉ์ด๋‹ค. ์น˜ํ‚จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•  ๋•Œ๋งˆ๋‹ค ๋ˆ„์ ํ•˜์—ฌ ๋”ํ•œ๋‹ค.
    • ๋ชจ๋“  ์กฐํ•ฉ์— ๋Œ€ํ•œ ๋„์‹œ์˜ ์น˜ํ‚จ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜๊ณ , ์ด ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ printํ•œ๋‹ค.
  import sys
  from itertools import combinations
  si = sys.stdin.readline


  def get_city_chicken_len(chicken):
    ccl = 0
    for x, y in houses:
      cl = float('inf')
      for i, j in chicken:
        cl = min(cl, abs(x - i) + abs(y - j))

      ccl += cl
    return ccl


  n, m = map(int, si().split())
  houses = []
  chickens = []

  for i in range(n):
    line = si().split()
    for j in range(n):
      if line[j] == '1':
        houses.append([i, j])
      elif line[j] == '2':
        chickens.append([i, j])

  res = float('inf')
  for chicken in list(combinations(chickens, m)):
    res = min(res, get_city_chicken_len(chicken))

  print(res)