๐Ÿ–ฅ CS/Algorithm

[Algorithm] ํž™ | ์ตœ๋Œ€ ํž™, ์ตœ์†Œ ํž™

heap์ด๋ž€?

: ์šฐ์„  ์ˆœ์œ„ ํ(priority queue)๋ฅผ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉํ•˜๋Š” ์ž๋ฃŒ๊ตฌ์กฐ ์ค‘ ํ•˜๋‚˜๋กœ, ์™„์ „์ด์ง„ํŠธ๋ฆฌ๋ฅผ base๋กœ ํ•œ ์ž๋ฃŒ๊ตฌ์กฐ.

  • ์šฐ์„ ์ˆœ์œ„ ํ๋Š” ์šฐ์„ ์ˆœ์œ„๊ฐ€ ๊ฐ€์žฅ ๋†’์€ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์žฅ ๋จผ์ € ์‚ญ์ œํ•˜๋Š” ์ ์ด ํŠน์ง•
  • ์ตœ์†Œ ํž™: ๋ถ€๋ชจ ๋…ธ๋“œ์˜ ํ‚ค ๊ฐ’์ด ์ž์‹ ๋…ธ๋“œ์˜ ํ‚ค ๊ฐ’๋ณด๋‹ค ํ•ญ์ƒ ์ž‘์€ ํž™
  • ์ตœ๋Œ€ ํž™: ๋ถ€๋ชจ ๋…ธ๋“œ์˜ ํ‚ค ๊ฐ’์ด ์ž์‹ ๋…ธ๋“œ์˜ ํ‚ค ๊ฐ’๋ณด๋‹ค ํ•ญ์ƒ ํฐ ํž™

 

์ž๋ฃŒ๊ตฌ์กฐ ์ถ”์ถœ๋˜๋Š” ๋ฐ์ดํ„ฐ
์Šคํƒ(stack) ๊ฐ€์žฅ ๋‚˜์ค‘์— ์‚ฝ์ž…๋œ ๋ฐ์ดํ„ฐ
ํ(queue) ๊ฐ€์žฅ ๋จผ์ € ์‚ฝ์ž…๋œ ๋ฐ์ดํ„ฐ
์šฐ์„ ์ˆœ์œ„ ํ(priority queue) ๊ฐ€์žฅ ์šฐ์„  ์ˆœ์œ„๊ฐ€ ๋†’์€ ๋ฐ์ดํ„ฐ

 

์ตœ์†Œ ํž™ (min heap)

: ๊ฐ’์ด ๊ฐ€์žฅ ๋‚ฎ์€ ๋ฐ์ดํ„ฐ๊ฐ€ ๋จผ์ € ์‚ญ์ œ

import heapq 

heap = [] 

heapq.heappush(heap, 5) 
heapq.heappush(heap, 1) 
heapq.heappush(heap, 2) 

print(heap) # [1, 5, 2] 
print(heapq.heappop(heap)) # 1

 

์ตœ๋Œ€ ํž™ (max heap)

: ๊ฐ’์ด ํฐ ๋ฐ์ดํ„ฐ๊ฐ€ ๊ฐ€์žฅ ๋จผ์ € ์‚ญ์ œ

  • Python์—์„œ ํž™ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์‚ฌ์šฉ ์‹œ์—๋Š” default ๊ฐ’์ด ์ตœ์†Œ ํž™์œผ๋กœ ๋˜์–ด์žˆ์œผ๋ฏ€๋กœ, ์ตœ๋Œ€ ํž™์œผ๋กœ ์‚ฌ์šฉ ์‹œ์—๋Š”, ๊ฐ’์— ์Œ์ˆ˜ ๋ถ€ํ˜ธ(-)๋ฅผ ๋ถ™์—ฌ์„œ ๋„ฃ์—ˆ๋‹ค๊ฐ€, ๊ฐ’์„ ์ถ”์ถœ ์‹œ์— ๋‹ค์‹œ ์Œ์ˆ˜ ๋ถ€ํ˜ธ(-)๋ฅผ ๋ถ™์—ฌ ์›๋ž˜์˜ ๊ฐ’์œผ๋กœ ๋˜๋Œ๋ฆฐ๋‹ค.
import heapq

heap = [] # ํ˜„์žฌ: 5, 1, 2๋ฅผ ์ตœ๋Œ€ ํž™์— ๋„ฃ๊ณ  ์‹ถ์€ ์ƒํƒœ.
heapq.heappush(heap, -5)
heapq.heappush(heap, -1)
heapq.heappush(heap, -2)

print(heap) # [-5, -1, -2]
print(-heapq.heappop(heap)) # 5