Search

์ตœ์†Œํž™/์ตœ๋Œ€ํž™

Created At
2023/04/03 15:43
Updated At
2023/04/03 15:44
๋ถ„๋ฅ˜
์ž๋ฃŒ๊ตฌ์กฐ
ํž™์€ ์™„์ „์ด์ง„ํŠธ๋ฆฌ์˜ ์ผ์ข…์œผ๋กœ, ์ตœ๋Œ“๊ฐ’ ๋˜๋Š” ์ตœ์†Ÿ๊ฐ’ ์„ ๋น ๋ฅด๊ฒŒ ์ฐพ๋Š” ์ž๋ฃŒ๊ตฌ์กฐ์ด๋‹ค.
ํ‚ค ๊ฐ’์˜ ๋Œ€์†Œ๊ด€๊ณ„๋Š” ๋ถ€๋ชจ/์ž์‹ ๊ฐ„์—๋งŒ ์„ฑ๋ฆฝํ•˜๊ณ , ํ˜•์ œ๊ฐ„์—๋Š” ์„ฑ๋ฆฝํ•˜์ง€ ์•Š๋Š”๋‹ค.
cf. ์šฐ์„ ์ˆœ์œ„ ํ
์šฐ์„ ์ˆœ์œ„๊ฐ€ ๋†’์€ ๋ฐ์ดํ„ฐ๋ฅผ ๋จผ์ € ๋ฝ‘๋Š” ์šฐ์„ ์ˆœ์œ„ ํ ๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ,๋ฐฐ์—ด/ ์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ/ ํž™์ด ์žˆ์ง€๋งŒ ๋ณดํ†ต์€ ํž™์œผ๋กœ ์šฐ์„ ์ˆœ์œ„ ํ๋ฅผ ๊ตฌํ˜„ํ•˜๊ฒŒ ๋œ๋‹ค.
์ตœ์†Œ ํž™ (min heap)
ํž™์€ ๋‚ด๋ถ€์ ์œผ๋กœ ๋ฐฐ์—ด๋กœ ๊ตฌํ˜„๋ผ์žˆ๋‹ค. ๋”ฐ๋ผ์„œ ํŒŒ์ด์ฌ์˜ heapq ๋ชจ๋“ˆ์˜ ๋ฉ”์„œ๋“œ๋“ค๋„ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋Œ€์ƒ์œผ๋กœ ๋ฐ”๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.
heapq ๋Š” ๋””ํดํŠธ๋กœ ์ตœ์†Œ ํž™์„ ๋‹ค๋ฃฌ๋‹ค. ๋”ฐ๋ผ์„œ ๋ณ„ ๋‹ค๋ฅธ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ค„ ํ•„์š”์—†์ด heapq ๋ฅผ ์จ์ฃผ๋ฉด ๋œ๋‹ค.
โ€ข
heapq.heappush(heap, item) : item์„ heap์— ์ถ”๊ฐ€
โ€ข
heapq.heappop(heap) : heap์—์„œ ๊ฐ€์žฅ ์ž‘์€ ์›์†Œ๋ฅผ pop & ๋ฆฌํ„ด. ๋น„์–ด ์žˆ๋Š” ๊ฒฝ์šฐ IndexError๊ฐ€ ํ˜ธ์ถœ๋จ.
โ€ข
heapq.heapify(x) : ๋ฆฌ์ŠคํŠธ x๋ฅผ ์ฆ‰๊ฐ์ ์œผ๋กœ heap์œผ๋กœ ๋ณ€ํ™˜ํ•จ (in linear time,ย O(N)ย )
import heapq # 1. ๋นˆ ๋ฆฌ์ŠคํŠธ์— ์ตœ์†Œํž™์œผ๋กœ item ์ถ”๊ฐ€ heap = [] heapq.heappush(heap, 50) heapq.heappush(heap, 10) heapq.heappush(heap, 20) print(heap) # [10, 50, 20] # 2. ๊ธฐ์กด๋ฆฌ์ŠคํŠธ๋ฅผ ์ตœ์†Œํž™์œผ๋กœ ๋งŒ๋“ค๊ธฐ heap2 = [50 ,10, 20] heapq.heapify(heap2) print(heap2) # [10, 50, 20] # 3. ๊ฐ€์žฅ ์ž‘์€ ์›์†Œ(0๋ฒˆ์ธ๋ฑ์Šค) ์ œ๊ฑฐ result = heapq.heappop(heap) print(result) # 10 print(heap) # [20, 50] # 4. ๊ทธ๋ƒฅ ์ž‘์€ ์›์†Œ๋งŒ ๊ฐ€์ ธ์˜ค๊ณ  ์‹ถ๋‹ค๋ฉด 0๋ฒˆ์ธ๋ฑ์Šค๋กœ ๊ฐ€์ ธ์˜ค๊ธฐ result2 = heap[0]
Python
๋ณต์‚ฌ
์ตœ๋Œ€ ํž™(max heap)
์ตœ๋Œ€ ํž™์„ ์œ„ํ•œ ๋ณ„๋„์˜ ๋ชจ๋“ˆ์€ ์—†๊ณ , ์ตœ์†Œ ํž™(heaap) ๋ฅผ ์ด์šฉํ•ด์„œ ๋งŒ๋“ ๋‹ค.
๊ฐ ์›์†Œ๋“ค์— ๋Œ€ํ•ด ๋ชจ๋‘ ์Œ์ˆ˜๋ฅผ ์ทจํ•ด์ฃผ๊ณ  ์ตœ์†Œ ํž™์œผ๋กœ ๋งŒ๋“ค๊ณ , ๊บผ๋‚ผ๋•Œ๋งŒ ๋‹ค์‹œ ์Œ์ˆ˜๋ฅผ ์ทจํ•ด์„œ ์›๋ž˜ ์ˆ˜๋กœ ๋ณต์›ํ•ด์ฃผ๋ฉด ๊ทธ๊ฒŒ ์ตœ๋Œ€ ํž™์ด๋‹ค.
์ด ๋•Œ ์Œ์ˆ˜๋ฅผ ์ทจํ•ด์ฃผ๊ณ  ๋ณต์›ํ•ด์ฃผ๋Š”๊ฒŒ ๊ท€์ฐฎ์œผ๋ฏ€๋กœ (-item, item) ์‹์˜ ํŠœํ”Œ์„ ์‚ฌ์šฉํ•˜๋ฉด ํŽธ๋ฆฌํ•˜๋‹ค.
heap_items = [1,3,5,7,9] max_heap = [] for item in heap_items: heapq.heappush(max_heap, (-item, item)) print(max_heap) # [(-9, 9), (-7, 7), (-3, 3), (-1, 1), (-5, 5)] # ์‹ค์ œ ์›์†Œ๋Š” ํŠœํ”Œ์˜ 1๋ฒˆ ์ธ๋ฑ์Šค ๊ฐ’
Python
๋ณต์‚ฌ