๐ŸŒฑ → ๐ŸŒณ

[Python] ํž™ ์ž๋ฃŒ๊ตฌ์กฐ / ํž™ํ(heapq) / ํŒŒ์ด์ฌ์—์„œ heapq ๋ชจ๋“ˆ ์‚ฌ์šฉ ๋ณธ๋ฌธ

Algorithms

[Python] ํž™ ์ž๋ฃŒ๊ตฌ์กฐ / ํž™ํ(heapq) / ํŒŒ์ด์ฌ์—์„œ heapq ๋ชจ๋“ˆ ์‚ฌ์šฉ

BAY 2023. 5. 30. 13:17
728x90

ํž™์€ ํŠน์ •ํ•œ ๊ทœ์น™์„ ๊ฐ€์ง€๋Š” ํŠธ๋ฆฌ๋กœ, ์ตœ๋Œ“๊ฐ’๊ณผ ์ตœ์†Ÿ๊ฐ’์„ ์ฐพ๋Š” ์—ฐ์‚ฐ์„ ๋น ๋ฅด๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•ด ๊ณ ์•ˆ๋œ ์™„์ „์ด์ง„ํŠธ๋ฆฌ๋ฅผ ๊ธฐ๋ณธ์œผ๋กœ ํ•œ๋‹ค. 

ํž™ property : A๊ฐ€ B์˜ ๋ถ€๋ชจ๋…ธ๋“œ์ด๋ฉด A์˜ ํ‚ค๊ฐ’๊ณผ B์˜ ํ‚ค๊ฐ’ ์‚ฌ์ด์—๋Š” ๋Œ€์†Œ ๊ด€๊ณ„๊ฐ€ ์„ฑ๋ฆฝํ•œ๋‹ค

  • ์ตœ์†Œ ํž™: ๋ถ€๋ชจ ๋…ธ๋“œ์˜ ํ‚ค๊ฐ’์ด ์ž์‹ ๋…ธ๋“œ์˜ ํ‚ค๊ฐ’๋ณด๋‹ค ํ•ญ์ƒ ์ž‘์€ ํž™
  • ์ตœ๋Œ€ ํž™: ๋ถ€๋ชจ ๋…ธ๋“œ์˜ ํ‚ค๊ฐ’์ด ์ž์‹ ๋…ธ๋“œ์˜ ํ‚ค๊ฐ’๋ณด๋‹ค ํ•ญ์ƒ ํฐ ํž™

 

์ด๋Ÿฌํ•œ ์†์„ฑ์œผ๋กœ ์ธํ•ด ํž™์—์„œ๋Š” ๊ฐ€์žฅ ๋‚ฎ์€(ํ˜น์€ ๋†’์€) ์šฐ์„ ์ˆœ์œ„๋ฅผ ๊ฐ€์ง€๋Š” ๋…ธ๋“œ๊ฐ€ ํ•ญ์ƒ ๋ฃจํŠธ์— ์˜ค๊ฒŒ ๋˜๊ณ  ์ด๋ฅผ ์ด์šฉํ•ด ์šฐ์„ ์ˆœ์œ„ ํ์™€ ๊ฐ™์€ ์ถ”์ƒ์  ์ž๋ฃŒํ˜•์„ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค. 

์ด๋•Œ ํ‚ค๊ฐ’์˜ ๋Œ€์†Œ ๊ด€๊ณ„๋Š” ๋ถ€๋ชจ/์ž์‹ ๊ฐ„์—๋งŒ ์„ฑ๋ฆฝํ•˜๊ณ , ํ˜•์ œ๋…ธ๋“œ ์‚ฌ์ด์—๋Š” ๋Œ€์†Œ ๊ด€๊ณ„๊ฐ€ ์ •ํ•ด์ง€์ง€ ์•Š๋Š”๋‹ค.

 

ํŒŒ์ด์ฌ ํž™ ์ž๋ฃŒ๊ตฌ์กฐ

ํŒŒ์ด์ฌ heapq ๋ชจ๋“ˆ์€ heapq (priority queue) ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ œ๊ณตํ•œ๋‹ค.

๋ชจ๋“  ๋ถ€๋ชจ ๋…ธ๋“œ๋Š” ๊ทธ์˜ ์ž์‹ ๋…ธ๋“œ๋ณด๋‹ค ๊ฐ’์ด ์ž‘๊ฑฐ๋‚˜ ํฐ ์ด์ง„ํŠธ๋ฆฌ(binary tree) ๊ตฌ์กฐ์ธ๋ฐ, ๋‚ด๋ถ€์ ์œผ๋กœ๋Š” ์ธ๋ฑ์Šค 0์—์„œ ์‹œ์ž‘ํ•ด k๋ฒˆ์งธ ์›์†Œ๊ฐ€ ํ•ญ์ƒ ์ž์‹ ์›์†Œ๋“ค(2k+1, 2k+2) ๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ตœ์†Œ ํž™์˜ ํ˜•ํƒœ๋กœ ์ •๋ ฌ๋œ๋‹ค.   

heapq๋Š” ๋‚ด์žฅ ๋ชจ๋“ˆ๋กœ ๋ณ„๋„์˜ ์„ค์น˜ ์ž‘์—… ์—†์ด ๋ฐ”๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

 

ํž™ ํ•จ์ˆ˜ ํ™œ์šฉํ•˜๊ธฐ

  • heapq.heappush(heap, item) : item์„ heap์— ์ถ”๊ฐ€
  • heapq.heappop(heap) : heap์—์„œ ๊ฐ€์žฅ ์ž‘์€ ์›์†Œ๋ฅผ pop & ๋ฆฌํ„ด. ๋น„์–ด ์žˆ๋Š” ๊ฒฝ์šฐ IndexError๊ฐ€ ํ˜ธ์ถœ๋จ. 
  • heapq.heapify(x) : ๋ฆฌ์ŠคํŠธ x๋ฅผ ์ฆ‰๊ฐ์ ์œผ๋กœ heap์œผ๋กœ ๋ณ€ํ™˜ํ•จ (in linear time, O(N) )

 

์ตœ๋Œ€ ํž™ ๋งŒ๋“ค๊ธฐ

ํŒŒ์ด์ฌ์˜ heapq ๋ชจ๋“ˆ์€ ์ตœ์†Œ ํž™์œผ๋กœ ๊ตฌํ˜„๋˜์–ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ตœ๋Œ€ ํž™ ๊ตฌํ˜„์„ ์œ„ํ•ด์„œ๋Š” ํŠธ๋ฆญ์ด ํ•„์š”ํ•˜๋‹ค.

IDEA: y = -x ๋ณ€ํ™˜์„ ํ•˜๋ฉด ์ตœ์†Ÿ๊ฐ’ ์ •๋ ฌ์ด ์ตœ๋Œ“๊ฐ’ ์ •๋ ฌ๋กœ ๋ฐ”๋€๋‹ค.

ํž™์— ์›์†Œ๋ฅผ ์ถ”๊ฐ€ํ•  ๋•Œ (-item, item)์˜ ํŠœํ”Œ ํ˜•ํƒœ๋กœ ๋„ฃ์–ด์ฃผ๋ฉด ํŠœํ”Œ์˜ ์ฒซ ๋ฒˆ์งธ ์›์†Œ๋ฅผ ์šฐ์„ ์ˆœ์œ„๋กœ ํž™์„ ๊ตฌ์„ฑํ•˜๊ฒŒ ๋œ๋‹ค. 

์ด๋•Œ ์›์†Œ ๊ฐ’์˜ ๋ถ€ํ˜ธ๋ฅผ ๋ฐ”๊ฟจ๊ธฐ ๋•Œ๋ฌธ์—, ์ตœ์†Œ ํž™์œผ๋กœ ๊ตฌํ˜„๋œ heapq ๋ชจ๋“ˆ์„ ์ตœ๋Œ€ ํž™ ๊ตฌํ˜„์— ํ™œ์šฉํ•˜๊ฒŒ ๋˜๋Š” ๊ฒƒ์ด๋‹ค.

์•„๋ž˜์˜ ์˜ˆ์‹œ๋Š” ๋ฆฌ์ŠคํŠธ heap_items์— ์žˆ๋Š” ์›์†Œ๋“ค์„ max_heap์ด๋ผ๋Š” ์ตœ๋Œ€ ํž™ ์ž๋ฃŒ๊ตฌ์กฐ๋กœ ๋งŒ๋“œ๋Š” ์ฝ”๋“œ์ด๋‹ค.

heap_items = [1,3,5,7,9]

max_heap = []
for item in heap_items:
  heapq.heappush(max_heap, (-item, item))

print(max_heap)

 

์ฐธ๊ณ 

https://littlefoxdiary.tistory.com/3

728x90