How to implement O(logn) decrease-key operation for min-heap based Priority Queue?

前端 未结 4 1584
孤街浪徒
孤街浪徒 2020-12-04 10:59

I am working on an application that demonstrates the Djikstra\'s algorithm, and to use it, I need to restore the heap property when my elements\' value is decreased

4条回答
  •  渐次进展
    2020-12-04 11:20

    I had implemented the same thing. In the MinHeap class, I had added a dictionary that is used to access the item in O(1). And on decrease key, it will be bubbled up in O(logn) time.

    class MinHeap:
    def __init__(self, array):
        self.heap = self.buildHeap(array)
        self.idx_of_element = {}
    
    def getParentIdx(self, idx):
        return (idx - 1) // 2
    
    def getLeftChildIdx(self, idx):
        return idx * 2 + 1
    
    def getRightChildIdx(self, idx):
        return idx * 2 + 2
    
    def buildHeap(self, array):
        # Write your code here.
        lastIdx = len(array) - 1
        startFrom = self.getParentIdx(lastIdx)
        for i in range(startFrom, -1, -1):
            self.siftDown(i, array)
        return array
    
    # this is min-heapify method
    def siftDown(self, idx, array):
        while True:
            l = self.getLeftChildIdx(idx)
            r = self.getRightChildIdx(idx)
    
            smallest = idx
            if l < len(array) and array[l] < array[idx]:
                smallest = l
            if r < len(array) and array[r] < array[smallest]:
                smallest = r
    
            if smallest != idx:
                array[idx], array[smallest] = array[smallest], array[idx]
                self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[smallest]] = self.idx_of_element[self.heap[smallest]], self.idx_of_element[self.heap[idx]]
                idx = smallest
            else:
                break
    

提交回复
热议问题