JUNGLE 240326 (W01)

KRAFTON JUNGLE Week 01 (λ‚΄ 생일!!!🀍)

1. Keywords

μš°μ„ μˆœμœ„ 큐 (Priority Queue)

  • 큐의 각 μš”μ†Œμ— μš°μ„  μˆœμœ„κ°€ μ§€μ •λœ 자료 ꡬ쑰
  • 일반적으둜 κ°€μž₯ 높은 μš°μ„  μˆœμœ„λ₯Ό 가진 μš”μ†Œκ°€ λ¨Όμ € μ²˜λ¦¬λ˜λŠ” 자료 ꡬ쑰
  • νž™(heap) 자료 ꡬ쑰λ₯Ό μ‚¬μš©ν•˜μ—¬ κ΅¬ν˜„ν•  수 있음
class PriorityQueue:
    def __init__(self):
        self.heap = []

    def parent(self, i):
        return (i - 1) // 2   # λΆ€λͺ¨ λ…Έλ“œμ˜ 인덱슀

    def left_child(self, i):
        return 2 * i + 1      # μ™Όμͺ½ μžμ‹ λ…Έλ“œμ˜ 인덱슀

    def right_child(self, i):
        return 2 * i + 2      # 였λ₯Έμͺ½ μžμ‹ λ…Έλ“œμ˜ 인덱슀

    def swap(self, i, j):
        self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
  • __init__(): μš°μ„ μˆœμœ„ 큐 객체λ₯Ό μ΄ˆκΈ°ν™”
  • parent(): 주어진 인덱슀 i의 λΆ€λͺ¨ λ…Έλ“œμ˜ 인덱슀λ₯Ό λ°˜ν™˜
  • left_child(), right_child(): 주어진 인덱슀 i의 μ™Όμͺ½, 였λ₯Έμͺ½ μžμ‹ λ…Έλ“œμ˜ 인덱슀λ₯Ό λ°˜ν™˜
  • swap(): 주어진 인덱슀 i, j의 값을 μ„œλ‘œ κ΅ν™˜
    def heapify_up(self, i):
        while i > 0 and self.heap[self.parent(i)][0] > self.heap[i][0]:
            self.swap(i, self.parent(i))
            i = self.parent(i)

    def heapify_down(self, i):
        min_index = i
        left = self.left_child(i)
        right = self.right_child(i)

        if left < len(self.heap) and self.heap[left][0] < self.heap[min_index][0]:
            min_index = left

        if right < len(self.heap) and self.heap[right][0] < self.heap[min_index][0]:
            min_index = right

        if i != min_index:
            self.swap(i, min_index)
            self.heapify_down(min_index)
  • heapify_up(): 주어진 인덱슀 iλ₯Ό κΈ°μ€€μœΌλ‘œ λΆ€λͺ¨ λ…Έλ“œμ™€ λΉ„κ΅ν•˜μ—¬ νž™ 속성을 λ§Œμ‘±ν•˜λ„λ‘ μœ„λ‘œ μ˜¬λ €κ°€λ©° μ‘°μ • (μ‚½μž… μ—°μ‚° μ‹œ μ‚¬μš©)
  • heapify_down(): 주어진 인덱슀 iλ₯Ό κΈ°μ€€μœΌλ‘œ μžμ‹ λ…Έλ“œμ™€ λΉ„κ΅ν•˜μ—¬ νž™ 속성을 λ§Œμ‘±ν•˜λ„λ‘ μ•„λž˜λ‘œ λ‚΄λ €κ°€λ©° μ‘°μ • (μ‚­μ œ μ—°μ‚° μ‹œ μ‚¬μš©)
    def insert(self, priority, value):
        self.heap.append((priority, value))
        self.heapify_up(len(self.heap) - 1)

    def delete_min(self):
        if len(self.heap) == 0:
            return None
        if len(self.heap) == 1:
            return self.heap.pop()

        min_value = self.heap[0]
        self.heap[0] = self.heap.pop()
        self.heapify_down(0)
        return min_value
  • insert(): 주어진 μš°μ„ μˆœμœ„ priority와 κ°’ valueλ₯Ό 가진 μš”μ†Œλ₯Ό μš°μ„ μˆœμœ„ 큐에 μ‚½μž…
    • νž™μ— μƒˆλ‘œμš΄ μš”μ†Œκ°€ λ“€μ–΄ 였면, 일단 μƒˆλ‘œμš΄ λ…Έλ“œλ₯Ό νž™μ˜ λ§ˆμ§€λ§‰ λ…Έλ“œμ— μ‚½μž…
    • μ‚½μž… 후에 heapify_up을 ν˜ΈμΆœν•΄ μƒˆλ‘œμš΄ λ…Έλ“œλ₯Ό λΆ€λͺ¨ λ…Έλ“œλ“€κ³Ό κ΅ν™˜ν•΄μ„œ νž™μ˜ μ„±μ§ˆμ„ μœ μ§€
  • delete_min(): μš°μ„ μˆœμœ„κ°€ κ°€μž₯ 높은 μš”μ†Œλ₯Ό μ œκ±°ν•˜κ³  λ°˜ν™˜
    • μ΅œλŒ€ νž™μ—μ„œμ˜ μ‚­μ œλŠ” κ°€μž₯ 큰 킀값을 가진 λ…Έλ“œλ₯Ό μ‚­μ œν•˜λŠ” 것 (루트 λ…Έλ“œ μ‚­μ œ)
    • λ§ˆμ§€λ§‰ λ…Έλ“œλ₯Ό 루트 λ…Έλ“œλ‘œ μ΄λ™μ‹œν‚¨ ν›„ λ£¨νŠΈμ—μ„œλΆ€ν„° 단말 λ…Έλ“œκΉŒμ§€μ˜ κ²½λ‘œμ— μžˆλŠ” λ…Έλ“œλ“€μ„ κ΅ν™˜
    • 즉, heapify_down을 ν˜ΈμΆœν•΄ νž™μ˜ μ„±μ§ˆμ„ μœ μ§€