-
[๋ฐฑ์ค] 2343 ๊ธฐํ ๋ ์จ with PythonPS 2021. 10. 19. 21:52728x90๋ฐ์ํ
๐ BOJ 2343 ๊ธฐํ ๋ ์จ
๐ก ์กฐ๊ฑด
- ๊ฐ์์ ์ N
(1 โค N โค 100,000)
๋ธ๋ฃจ๋ ์ด์ ์ M(1 โค M โค N) - ๋ธ๋ฃจ๋ ์ด๋ฅผ ๋ นํํ ๋, ๊ฐ์์ ์์๊ฐ ๋ฐ๋๋ฉด ์ ๋๋ค.
- ๊ฐ ๊ฐ์์ ๊ธธ์ด๊ฐ ๋ถ ๋จ์(์์ฐ์)๋ก ์ฃผ์ด์ง๋ค. ๊ฐ๋ฅํ ๋ธ๋ฃจ๋ ์ด์ ํฌ๊ธฐ ์ค ์ต์๋ฅผ ๊ตฌํ๋ ๋ฌธ์ .
- ์ด๋ถํ์ ์๊ณ ๋ฆฌ์ฆ ์ ํ์ ๋ฌธ์
๐ฅ ์์ค ์ฝ๋
from sys import stdin n, m = map(int, stdin.readline().split()) arr = list(map(int, stdin.readline().split())) def get_cnt(): count = 0 temp = 0 for i in range(n): if temp + arr[i] > mid: count += 1 temp = 0 temp += arr[i] if temp: count += 1 return count left, right = max(arr), sum(arr) while left <= right: mid = (left + right) // 2 cnt = get_cnt() if cnt > m: left = mid + 1 elif cnt <= m: right = mid - 1 print(max(left, right, mid))๐ ์์ ๋ฐ ์คํ๊ฒฐ๊ณผ
์์
9 3 1 2 3 4 5 6 7 8 9์คํ๊ฒฐ๊ณผ
17โจ๏ธ ๋ฌธ์ ํ์ด
- ์ด๋ถํ์์ ์ํด
left,right,mid๋ณ์๋ฅผ ์ด๊ธฐํ ํด์ค๋๋ค.- left๋ ์ ๋ ฅ๋ฐ์ ๊ฐ์ ์๊ฐ ๋ฐฐ์ด์ ๊ฐ์ฅ ํฐ ๊ฐ
- right๋ ์ ๋ ฅ๋ฐ์ ๊ฐ์ ์๊ฐ ๋ฐฐ์ด์ ํฉ
- mid = (left + right) // 2
๋ธ๋ฃจ๋ ์ด์ ํฌ๊ธฐ์ ๋ช๊ฐ์ ๊ฐ์๊ฐ ๋ค์ด๊ฐ๋์ง ๊ฒ์ฌํ์ฌ ๋ฐํํ๋ ํจ์๋ฅผ ๋ง๋ค์ด์ค๋๋ค.
์ฌ๊ธฐ์ ๋ธ๋ฃจ๋ ์ด์ ํฌ๊ธฐ๋ mid๋ฅผ ๊ธฐ์ค์ผ๋ก ๊ฒ์ฌ๋ฅผ ํด์ค๋ค.def get_cnt(): count = 0 temp = 0 for i in range(n): if temp + arr[i] > mid: count += 1 temp = 0 temp += arr[i] if temp: count += 1 return count
left๋ณ์๊ฐright๋ณ์๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ์ ๋๊น์ง ๋ฐ๋ณตํ์ฌ ์งํํ ๋ค,left,right,mid์ค ๊ฐ์ฅ ํฐ ๊ฐ์ ์ถ๋ ฅํ๋ค.
๋ธ๋ฃจ๋ ์ด์ ํฌ๊ธฐ๊ฐ ๋ชจ๋ ๊ฐ์์ผํ๊ธฐ ๋๋ฌธ์ ์ต๋๊ฐ์ ์ถ๋ ฅํ๋ ๊ฒ์ด๋ค.
๐พ ๋๋์
- ์ด๋ถํ์์ ํตํด์ ํ์ด๋ด๋ ๋ฌธ์ ์๋ค.
- ๋ฌธ์ ๋ฅผ ์ดํดํ์ง ๋ชปํด์ ์กฐ๊ธ ํค๋งธ๋ ๋ฌธ์ ์๋ค.
get_cntํจ์๋ฅผ ๊ตฌํํ๋ ค๋ค๊ฐ ์์๊ฐ ๋ฐ๋๋ฉด ์๋๋ค๋ ์กฐ๊ฑด์ ๋ณด๊ณ ๊ตฌํํ ์ ์์๋ค.
๋ฐ์ํ'PS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 1043 ๊ฑฐ์ง๋ง with Python (0) 2021.10.20 [๋ฐฑ์ค] 3184 ์ with Python (0) 2021.10.19 [๋ฐฑ์ค] 1743 ์์๋ฌผ ํผํ๊ธฐ with Python (0) 2021.10.18 [๋ฐฑ์ค] 1713 ํ๋ณด ์ถ์ฒํ๊ธฐ with Python (0) 2021.10.18 [๋ฐฑ์ค] 1244 ์ค์์น ์ผ๊ณ ๋๊ธฐ with Python (0) 2021.10.17 - ๊ฐ์์ ์ N