How can I implement decrease-key functionality in Python's heapq?

前端 未结 4 945
故里飘歌
故里飘歌 2020-12-08 06:37

I know it is possible to realize decrease-key functionality in O(log n) but I don\'t know how?

4条回答
  •  有刺的猬
    2020-12-08 07:14

    The heapq documentation has an entry on exactly how to do this.

    However, I have written a heap package that does exactly this (it is a wrapper around heapq). So if you have pip or easy_install you could do something like

    pip install heap
    

    Then in your code write

    from heap.heap import heap
    
    h = heap()
    
    h['hello'] = 4 # Insert item with priority 4.
    
    h['hello'] = 2 # Update priority/decrease-key has same syntax as insert. 
    

    It is pretty new though, so might be full of bugs.

提交回复
热议问题