Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Decrease Key with STL heap in O(logn) time

Tags:

c++

stl

heap

At the moment STL Heap does not support decrease key, however one can just change the value on the vector directly and call make_heap again which is O(n) time. However that's not as efficient as a binary heap decrease key which would take O(logn) time.

Is there a way to achieve O(logn) time using STL heap functions?

like image 984
Jake Avatar asked Mar 24 '12 06:03

Jake


People also ask

What is decrease key operation in heap?

In this tutorial, we'll present a third operation called decrease-key, which allows us to decrease the value of a certain key inside the data structure. Mainly, the decrease-key operation is used in Dijkstra's algorithm when we discover a new path to a certain node at a lower cost.

What is the time complexity of insertion and deletion in priority queue implemented as binary heap?

It will take O(log N) time to insert and delete each element in the priority queue. Based on heap structure, priority queue also has two types max- priority queue and min - priority queue.

How is heap implemented in STL?

Heap data structure can be implemented in a range using STL which allows faster input into heap and retrieval of a number always results in the largest number i.e. largest number of the remaining numbers is popped out each time. Other numbers of the heap are arranged depending upon the implementation.


1 Answers

I'm pretty sure there's no standard-conforming way of doing it - Wikipedia says so too:

there is no standard support for the decrease/increase-key operation

Although it does go on to point to the gheap library, which might well be worth a look.

The problem here is that the standard does not mandate what form the heap structure takes, nor how exactly the operations are performed. (In general this is a good thing.)

If the implementation is using a standard binary heap then I think you can simply decrease the element at heap[i] and then call push_heap(heap.begin(), heap.begin() + i + 1), which will do the necessary up-heap operation. The element that ends up at position i must have been no larger than the value there originally, and so the heap property of the whole heap is preserved. But this is not supported by the standard even if it does work sometimes in some implementations.

like image 143
Alan Stokes Avatar answered Sep 21 '22 06:09

Alan Stokes