๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
4๏ธโƒฃ Python/Problem Solving

[Python Algorithm] ๊ฐ€์šด๋ฐ๋ฅผ ๋งํ•ด์š” BOJ #1655

by seolhee2750 2022. 6. 14.
๋ฌธ์ œ

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

 

1655๋ฒˆ: ๊ฐ€์šด๋ฐ๋ฅผ ๋งํ•ด์š”

์ฒซ์งธ ์ค„์—๋Š” ๋ฐฑ์ค€์ด๊ฐ€ ์™ธ์น˜๋Š” ์ •์ˆ˜์˜ ๊ฐœ์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค. N์€ 1๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 100,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ž์—ฐ์ˆ˜์ด๋‹ค. ๊ทธ ๋‹ค์Œ N์ค„์— ๊ฑธ์ณ์„œ ๋ฐฑ์ค€์ด๊ฐ€ ์™ธ์น˜๋Š” ์ •์ˆ˜๊ฐ€ ์ฐจ๋ก€๋Œ€๋กœ ์ฃผ์–ด์ง„๋‹ค. ์ •์ˆ˜๋Š” -1

www.acmicpc.net

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import sys
import heapq

n = int(sys.stdin.readline().strip())
left = []
right = []

for _ in range(n):
    now = int(sys.stdin.readline().strip())

    if len(left) == len(right):
        heapq.heappush(left, -now)
    else:
        heapq.heappush(right, now)

    if right and right[0] < -left[0]:
        leftNum = heapq.heappop(left)
        rightNum = heapq.heappop(right)

        heapq.heappush(left, -rightNum)
        heapq.heappush(right, -leftNum)

    print(-left[0])

๐Ÿ‘‰ ํž™ ๋ฌธ์ œ

  • ์ค‘๊ฐ„ ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ์ž‘์€ ๊ฐ’์€ left ๋ฆฌ์ŠคํŠธ์—, ํฐ ๊ฐ’์€ right ๋ฆฌ์ŠคํŠธ์— ์ €์žฅํ•ด์ฃผ์—ˆ๋‹ค.
    ์ตœ์†Œ ํž™์˜ ๊ฒฝ์šฐ ๋ฃจํŠธ ๋…ธ๋“œ์— ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ ์ €์žฅํ•˜๊ณ , ์ตœ๋Œ€ ํž™์˜ ๊ฒฝ์šฐ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ์ €์žฅํ•˜๊ธฐ ๋•Œ๋ฌธ์—
    left ๋ฆฌ์ŠคํŠธ๋Š” ์ตœ์†Œ ํž™์œผ๋กœ, right ๋ฆฌ์ŠคํŠธ๋Š” ์ตœ๋Œ€ ํž™์œผ๋กœ ๋งŒ๋“ค์–ด์„œ ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ํ†ตํ•ด ํฌ๊ณ  ์ž‘์Œ์„ ๋น„๊ตํ–ˆ๋‹ค.
    (์ฒ˜์Œ์—๋Š” ํž™ ์ •๋ ฌ์„ ์ด์šฉํ–ˆ์ง€๋งŒ, ์ƒ๊ฐํ•ด๋ณด๋‹ˆ ๊ตณ์ด ๋ชจ๋“  ์ˆ˜๋ฅผ ๋น„๊ตํ•  ํ•„์š”๊ฐ€ ์—†๊ณ 
    ์ค‘๊ฐ„ ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ํฐ ๊ฐ’๊ณผ ์ž‘์€ ๊ฐ’๋งŒ ๋น„๊ตํ•ด์ฃผ๋ฉด ๋˜์—ˆ๊ธฐ ๋•Œ๋ฌธ์— ์œ„์™€ ๊ฐ™์€ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ–ˆ๋‹ค.)
  • left์™€ right์˜ ๊ธธ์ด๊ฐ€ ๊ฐ™์„ ๊ฒฝ์šฐ ํ˜„์žฌ ์ž…๋ ฅ๋˜๋Š” ๊ฐ’์„ ํฌํ•จํ•˜์—ฌ ํ™€์ˆ˜๊ฐœ์˜ ์ˆ˜๊ฐ€ ์ž…๋ ฅ๋˜์—ˆ๋‹ค๋Š” ๋œป์ด๋ฏ€๋กœ
    left ๋ฆฌ์ŠคํŠธ์— ๊ฐ’์„ heappush ํ–ˆ๊ณ , ๊ทธ ์™ธ์˜ ๊ฒฝ์šฐ right ๋ฆฌ์ŠคํŠธ์— ๊ฐ’์„ heappush ํ–ˆ๋‹ค.
  • ๊ทธ๋ฆฌ๊ณ  ํ˜น์‹œ right์˜ ๋ฃจํŠธ ๋…ธ๋“œ ๊ฐ’์ด left์˜ ๋ฃจํŠธ ๋…ธ๋“œ ๊ฐ’๋ณด๋‹ค ๋” ์ž‘์„ ๊ฒฝ์šฐ,
    ์ค‘๊ฐ„ ๊ฐ’๋ณด๋‹ค ์ž‘์€ ๊ฐ’์ด right์— ๋“ค์–ด๊ฐ”๋‹ค๋Š” ๋œป์ด๋ฏ€๋กœ ๋‘ ์ˆ˜๋ฅผ ๊ตํ™˜ํ•ด์ฃผ์—ˆ๋‹ค.
  • ์—ฐ์‚ฐ์ด ๋๋‚˜๋ฉด left ๋ฆฌ์ŠคํŠธ์˜ ๋ฃจํŠธ ๋…ธ๋“œ ๊ฐ’์„ ์ถœ๋ ฅํ•ด์ฃผ์—ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์ฒ˜์Œ์—” ํž™ ์ •๋ ฌ์ด๋ผ๊ณ  ์ƒ๊ฐํ•ด์„œ ํ’€์—ˆ๋Š”๋ฐ, ์‹œ๊ฐ„ ์ดˆ๊ณผ์˜€๋‹ค.
    ์•Œ๊ณ ๋ณด๋‹ˆ ๊ตณ์ด ๋‹ค ์ •๋ ฌํ•  ํ•„์š”๊ฐ€ ์—†๊ณ , ์ค‘๊ฐ„ ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ๋” ํฐ ๊ฐ’๊ณผ ์ž‘์€ ๊ฐ’๋งŒ ๋น„๊ตํ•ด์ฃผ๋ฉด ๋˜๋Š” ๋ฌธ์ œ์˜€๋‹ค.
  • ํž™์˜ ๊ฐœ๋…์„ ์ž˜ ์•Œ์•„์•ผ ํ•˜๊ณ , ์ตœ๋Œ€ ํž™๊ณผ ์ตœ์†Œ ํž™์„ ๋งŒ๋“ค ์ค„ ์•Œ๋ฉด ๋˜๋Š” ๋ฌธ์ œ๊ฐ™๋‹ค.
    ๋‚˜๋Š” ์ž˜ ๋ชฐ๋ผ์„œ ๊ณต๋ถ€ํ•˜๋ฉด์„œ ํ’€์—ˆ๊ณ ,,! ์ด์ œ ํž™์„ ์ข€ ์‚ฌ์šฉํ• ์ค„ ์•Œ๊ฒŒ ๋œ ๊ฒƒ ๊ฐ™๋‹ค.

๋Œ“๊ธ€