๐ฉ๐ปโ๐ป๋ฌธ์ ๋งํฌ
[๋ฐฑ์ค 15686] ์นํจ ๋ฐฐ๋ฌ (Python)
โ๏ธIdea Sketch
2021-08-10
1. ์ถ๋ ฅ๊ฐ ๋ถ์ํ๊ธฐ
- ์นํจ๊ฑฐ๋ฆฌ : ์ง๊ณผ ๊ฐ์ฅ ๊ฐ๊น์ด ์นํจ์ง ์ฌ์ด์ ๊ฑฐ๋ฆฌ
- ์ง
(x1, y1)
, ์นํจ์ง(x2, y2)
์ผ ๋, ์นํจ๊ฑฐ๋ฆฌ๋|x1-x2| + |y1-y2|
์ด๋ค. - ๋์์ ์นํจ๊ฑฐ๋ฆฌ : ๋ชจ๋ ์นํจ๊ฑฐ๋ฆฌ์ ํฉ
- ๋์์ ์นํจ๊ฑฐ๋ฆฌ์ ์ต์๊ฐ์?
2. ์ ๋ ฅ๊ฐ ๋ถ์ํ๊ธฐ
- ๋์์ ํฌ๊ธฐ๋ n*n ์ด๋ค.
- ์นํจ์ง์ m๊ฐ ๋นผ๊ณ ๋ค ํ์ ํ ์์ ์ด๋ค.
- 0์ ๋น์นธ์ด๋ค.
- 1์ ์ง์ด๋ค.
- 2๋ ์นํจ์ง์ด๋ค.
3. ๋ก์ง ์ดํด๋ณด๊ธฐ
- ์นํจ์ง์ด 5๊ฐ๊ณ , m์ด 2์ธ ๊ฒฝ์ฐ
- ์นํจ์ง 5๊ฐ ์ค์ 2๊ฐ๋ฅผ ๊ณ ๋ฅด๋ ๋ชจ๋ ์กฐํฉ์
combinations
๋ก ๊ตฌํ๋ค. city_length()
์์ ์นํจ๊ฑฐ๋ฆฌmin_length
์ ๋์์ ์นํจ๊ฑฐ๋ฆฌtotal
์ ๊ตฌํ๋ค.- ๋์์ ์นํจ๊ฑฐ๋ฆฌ์ ์ต์๊ฐ
result
๋ฅผ ๊ตฌํ๋ค.
โ๏ธ์์ค์ฝ๋
2021-08-10 356ms ํต๊ณผ
import sys from itertools import combinations def city_length(shops): total = 0 for house_x, house_y in houses: min_length = sys.maxsize for shop_x, shop_y in shops: length = abs(house_x - shop_x) + abs(house_y - shop_y) min_length = min_length if min_length < length else length total += min_length return total if __name__ == '__main__': n, m = map(int, input().split()) houses = [] shops = [] for i in range(n): line = input().split() for j in range(n): if line[j] == '1': houses.append([i, j]) elif line[j] == '2': shops.append([i, j]) result = sys.maxsize for shops in list(combinations(shops, m)): total = city_length(shops) result = result if result < total else total print(result)