Data-Structure[0] - Priority Queue와 Heap

Priority Queue(우선순위 큐)

Priority queue

Methods

Priorty ADT는 다음의 Method를 지원한다.

Pitfall: Priority가 높다 ==> k가 낮다.

heap을 이용하면 가장 성능이 좋은 우선순위 큐를 구현할 수 있다.

Heap(힙)

Heap (data structure)

Python heapq 라이브러리

python heapq

heap을 구현하기 위해 주로 리스트 구조를 이용한다.

heapq 라이브러리는 기본적으로 min heap구조를 가지고 있다.

heapq를 이용하여 우선순위 큐를 구현할 수 있다.

주요 method

import heapq

p_queue=[]

heapq.heappush(p_queue, (10, 'a'))
heapq.heappush(p_queue, (5, 'b'))
heapq.heappush(p_queue, (1, 'c'))
heapq.heappush(p_queue, (3, 'd'))
print(heapq.heappop(p_queue)) # (1, 'c')
print(heapq.heappop(p_queue)) # (3, 'd')
print(heapq.heappop(p_queue)) # (5, 'b')
print(heapq.heappop(p_queue)) # (10, 'a')

Time complexity

O(log n)