Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change max element in a heap in C++ standard library?

If I have a max heap, and if I need to change the max element, it comes down to a single bubble-down algorithm. Is there any way to do this via the C++ standard library, without coding the algorithm by hand?

I understand it should be equivalent to pop_heap + push_heap, but that's 2 bubble down operations instead of just one.

So - is this bubble-down algorithm exposed via the library API?

like image 880
rincewind Avatar asked Apr 15 '15 23:04

rincewind


People also ask

What is the maximum element in a max heap ()?

In a max-heap, the parent or root node is usually greater than the children nodes. The maximum element can be accessed in constant time since it is at index 1 . Based on the figure above, at every level, the largest number is the parent node.

How do you find the max element in heap?

Efficient approach:The min heap property requires that the parent node be lesser than its child node(s). Due to this, we can conclude that a non-leaf node cannot be the maximum element as its child node has a higher value. So we can narrow down our search space to only leaf nodes.


2 Answers

If you are willing to call std::pop_heap() on your own container v, then you can just first v.push_back() on the container the "modified" element before popping the heap. Then, shrink v.

// Precondition is that v is already a heap.
void change_max_element (std::vector<int> &v, int modified_value) {
    v.push_back(modified_value);
    std::pop_heap(v.begin(), v.end());
    v.pop_back();
}

This "works" because std::pop_heap() is defined to swap the first and last elements and bubble down. However, the requirement is also stated that the input sequence should be a valid heap. If we are able to define a specialized comparison operation that would allow the newly pushed back item to report itself to belong in the last position if it was already in the last position, then it could technically satisfy the requirement.

like image 187
jxh Avatar answered Sep 27 '22 16:09

jxh


The closest you'll get is std::make_heap, which is probably slower than simply pop/push.

However, boost heap(s?) have "The Fixup Interface" which allows modifications like you desire. http://www.boost.org/doc/libs/1_51_0/doc/html/heap/concepts.html#heap.concepts.mutability

like image 44
Mooing Duck Avatar answered Sep 27 '22 17:09

Mooing Duck