QHEAP1

  • + 0 comments
    class MinHeap:
        def __init__(self):
            self.heap = []
            
        def add(self, v):
            self.heap.append(v)
            self.__sift_up__(len(self.heap)-1)
            
        def delete(self, v):
            h = self.heap
            if h:
                try:
                    idx = self.heap.index(v)
                    h[idx], h[-1] = h[-1], h[idx]
                    h.pop()
                    if idx < len(h):
                        self.__sift_down__(idx)
                        self.__sift_up__(idx)
                except ValueError:
                    ...
                    
        def print_min(self):
            if self.heap:
                print(self.heap[0])
                
                
        def __sift_up__(self, idx):
            # compare and swap with parent upwards repeatedly: (idx-1)//2
            h = self.heap
            item = h[idx]
            while idx > 0:
                parent_idx = (idx-1)//2
                if item < h[parent_idx]:
                    h[idx] = h[parent_idx]
                    idx = parent_idx
                else:
                    break
            h[idx] = item
            
        def __sift_down__(self, idx):
            # compare and swap with children downwards repeatedly:
            h = self.heap
            size = len(h)
            item = h[idx]
            while True:
                l_idx, r_idx, min_idx = 2*idx+1, 2*idx+2, idx
                if l_idx < size and h[l_idx] < item:
                    min_idx = l_idx
                if r_idx < size and h[r_idx] < h[min_idx]:
                    min_idx = r_idx
                if min_idx != idx:
                    h[idx] = h[min_idx]
                    idx = min_idx
                else:
                    break
            h[idx] = item
        
    
    # Initialize the min-heap
    minHeap = MinHeap()
    
    # Number of operations
    num_of_queries = int(input())
    
    # Execute operations
    for _ in range(num_of_queries):
        op = input().split()
        op_code = op[0]
        if op_code == '1':
            minHeap.add(int(op[1]))
        elif op_code == '2':
            minHeap.delete(int(op[1]))
        elif op_code == '3':
            minHeap.print_min()