ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

heapq

์ด์ง„ํŠธ๋ฆฌ ๊ธฐ๋ฐ˜์˜ ์ตœ์†Œ ํž™ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ๋งŒ์•ฝ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์ •๋ ฌ๋œ ์ƒํƒœ๋กœ ์œ ์ง€ํ•  ํ•„์š”๊ฐ€ ์žˆ์„ ๊ฒฝ์šฐ ๊ณ„์†ํ•ด์„œ ์ •๋ ฌ์„ ํ•˜๋Š” ๊ฒƒ ๋ณด๋‹ค๋Š”, heapifyํ•˜๋Š” ๊ฒƒ์ด ํšจ์œจ์ ์ด๋‹ค.

import heapq

heap = []
heapq.heappush(heap, 7)
heapq.heappush(heap, 1)
heapq.heappush(heap, 5)
heapq.heappush(heap, 3)

heapq.heappop(heap)
  • ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ค๊ณ  ๋ฆฌ์ŠคํŠธ์— ๊ฐ’์„ ์‚ฝ์ž… ์‚ญ์ œ ํ•  ๊ฒฝ์šฐ, heapq์˜ ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ตœ์†Œํž™ ์„ฑ์งˆ์„ ๊ฐ€์ง„๋‹ค.
  • ์ตœ์†Œํž™์˜ ๊ฒฝ์šฐ, ๋ชจ๋“  ์›์†Œ(k)๋Š” ์ž์‹ ์›์†Œ๋“ค(2k+1, 2k+2) ๋ณด๋‹ค ํฌ๊ธฐ๊ฐ€ ์ž‘๋‹ค.
    • ๋”ฐ๋ผ์„œ ํ•ด๋‹น ์˜ˆ์ œ๋Š” [1, 3, 5, 7]๋กœ ์ •๋ ฌ๋˜์–ด ์ตœ์†Œํž™์ด ์œ ์ง€๋˜๊ฒŒ ๋œ๋‹ค.
  • heappop()์„ ํ•  ๊ฒฝ์šฐ, ๊ฐ’์„ ์‚ญ์ œํ•˜๊ณ  ๋ฃจํŠธ ๋…ธ๋“œ์˜ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
    • ๊ฐ’์„ ์‚ญ์ œํ•˜์ง€ ์•Š๊ณ  ๋ฃจํŠธ ๋…ธ๋“œ์˜ ๊ฐ’์„ ๊ฐ€์ ธ์˜ค๋ ค๋ฉด ๋ฆฌ์ŠคํŠธ ์ฒ˜๋Ÿผ heap[0]๋ฅผ ํ†ตํ•ด ์ ‘๊ทผํ•˜๋ฉด ๋œ๋‹ค.
heap = [1, 3, 9, 10, 4]
heapq.heapify(heap)
  • ๊ธฐ์กด์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ตœ์†Œํž™์œผ๋กœ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด์„œ๋Š” heapify๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

heapq ์‘์šฉ

์ตœ๋Œ€ ํž™

import heapq
heap = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] 
heapq._heapify_max(heap)
heapq._heappop_max(heap)
  • heapq ๋‚ด์—์„œ ์ œ๊ณตํ•˜๋Š” _heapify_max, _heappop_max๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด, ์ตœ๋Œ€ ํž™ ๊ตฌ์กฐ๋ฅผ ๊ฐ„๋žตํžˆ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.
    • ํ•˜์ง€๋งŒ ์ด ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜๋ฉด, heappush_max๊ฐ€ ์—†์–ด ์ถ”๊ฐ€, ์‚ญ์ œ๊ฐ€ ๊ณ„์† ํ•„์š”ํ•œ ๊ฒฝ์šฐ ์‚ฌ์šฉ์ด ๋ถˆ๊ฐ€๋Šฅํ•œ๋‹ค.
import heapq

nums = [1, 3, 9, 10, 4]
heap = []

for num in nums:
    heapq.heappush(heap, (-num, num))

root = heapq.heappop(heap)[1]
  • _heapify_max, heappop_max๋Š” ํž™์˜ ์›์†Œ๊ฐ€ ์‚ฝ์ž…, ์‚ญ์ œ๊ฐ€ ๋ฐ˜๋ณต๋˜๋Š” ๊ฒฝ์šฐ์—๋Š” ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค. ๋”ฐ๋ผ์„œ ๊ธฐ์กด์˜ ์ตœ์†Œํž™ ์„ฑ์งˆ๊ณผ ํŠœํ”Œ์„ ์ด์šฉํ•ด ๊ฐ„๋‹จํžˆ ์ตœ๋Œ€ ํž™์ฒ˜๋Ÿผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.
  • ํŠœํ”Œ์„ ์ด์šฉํ•ด (-num, num)๊ณผ ๊ฐ™์ด ์Œ์ˆ˜ ๊ฐ’์„ ๊ฐ™์ด ์‚ฝ์ž…ํ•œ๋‹ค.
  • ์ ‘๊ทผํ• ๋•Œ heappop(heap)[1]๋กœ ์ ‘๊ทผํ•˜์—ฌ ํŠœํ”Œ์˜ 2์—ด์— ์ ‘๊ทผํ•˜์—ฌ ์›๋ž˜์˜ ๊ฐ’์„ ๊ฐ€์ ธ์˜จ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€