λ€μμ λ³μλ€μ΄ μ‘΄μ¬νλ€κ³ κ°μ νλ€.
HEAP_SIZE = 0 # νμ μ‘΄μ¬νλ μμμ κ°μλ₯Ό μ μ₯ν λ³μ
heap = [None] # ν (0λ² μΈλ±μ€ λ―Έμ¬μ©)
# νμ μ½μ
μ. λ°λ³΅ μΈλ±μ€ iλ λ°©κΈ λ€μ΄κ° λ°μ΄ν°μ μΈλ±μ€λΆν° 루νΈμ μμκΉμ§
# 1. λ§μ§λ§ λ
Έλμ μ λ°μ΄ν°λ₯Ό μ½μ
# 2. (μ΅λ ν κΈ°μ€) λΆλͺ¨μ λΉκ΅ν΄μ λΆλͺ¨λ³΄λ€ ν¬λ©΄ λΆλͺ¨μ swap
# 3. λΆλͺ¨κ° λ ν° κ°μΌ λκΉμ§ 2λ²μ λ°λ³΅
def push(data):
global HEAP_SIZE
HEAP_SIZE += 1
heap.append(data)
i = HEAP_SIZE
while i > 1:
parent = i//2
if heap[i] <= heap[parent]:
break
heap[i], heap[parent] = heap[parent], heap[i]
i = parent
# νμμ μμ μ. μ ννλ μ°μ μμ νμμμ pop. κ°μ₯ ν° μμλ₯Ό κΊΌλ΄λ κ²
# 1. λ£¨νΈ λ
Έλ λ°μ΄ν°λ₯Ό κΊΌλ΄κ³ λ£¨νΈ λ
Έλ μμΉμ λ§μ§λ§ λ
Έλ κ°μ λ£λλ€.
# 2. λ§μ§λ§ λ
Έλλ₯Ό μμ μ²λ¦¬(ν ν¬κΈ°λ₯Ό 1 μ€μΈλ€).
# 3. νμ μ¬μ λ ¬νλ€.
def pop():
global HEAP_SIZE
data = heap[1]
heap[1] = heap[HEAP_SIZE]
heap.pop()
HEAP_SIZE -= 1
sort()
return data
# μ¬μ λ ¬: 루νΈλΆν° μμν΄μ λ§μ§λ§ λ
ΈλκΉμ§ λΉκ΅νλ©° swap
# λ΄κ° κ°μ₯ ν¬λ©΄ λ΄λΉλκ³ , λλ³΄λ€ ν° μμμ΄ μλ€λ©΄ λ ν° μμμ΄λ swapνλ€.
# λ μμμ΄ λͺ¨λ λλ³΄λ€ ν¬λ€λ©΄ λ μ€ λ ν° μμμ μλ‘ μ¬λ €μΌ max heapμ΄ μ μ§λλ€.
def sort():
global HEAP_SIZE
i = 1
while i*2 <= HEAP_SIZE:
max_index = i
if heap[max_index] < heap[i*2]:
max_index = i*2
if i*2 < HEAP_SIZE and heap[max_index] < heap[i*2+1]:
max_index = i*2+1
if max_index == i:
break
heap[max_index], heap[i] = heap[i], heap[max_index]
i = max_index