How to build a min heap with a remove function
As we know the C++ 11 provided us a lot of great functionalities. It is very convinect for us to use these functionalities to address our issues.
when I was trying to review the notations about the heap with an online algorithm problem;
It turns out I can use the Priority_queue
container to build a min heap
.
As we know, heap doesn’t provide a remove function to delete an arbitary element
. So first mission is to construct an our own priority_queue with a remove function.
But since the elements on heap is nearly ordered, we can not use some sort of binary search function to locate the element which we are going to delete. theoritically It looks
like we can not avoid a linear time to search the element.
After locating this element, the next step is to delete it and call std::make_queue
to let the all of elements to be a heap again.But the result is getting some time exceeding on
some test case.
So according the requiement of this problem,the tricky part is we don’t need to delete element until it is the first element.
The code looks like this: