I think you know which element in the heap container (index n) you want to delete.
- Set the value
v[n] = BIG; , the BIG value is really larger than any other values ​​on the heap. - Call
std::push_heap( v.begin(), v.begin()+n+1 ); - Call
std::pop_heap( v.begin(), v.end() ); - Call
v.pop_back(); - Done
Operation O (ln (n))
RE: confirmation request
First, the qualifier: This method assumes something about the algorithm used by std push_heap.
In particular, it is assumed that std push_heap (v.begin (), v.begin () + n + 1) will change the range [0, n]
for those elements that are descendants of n, i.e. indices in the following set:
A(n)={n,(n-1)/2,((n-1)/2-1)/2....0}.
Here is a typical specification for std push_heap:
http://www.cplusplus.com/reference/algorithm/push_heap/ "Given the heap range of [first, last-1], this function extends the range considered by the heap to [first, last] by putting the value in (last-1) to the appropriate place in it. "
Does this guarantee the use of the “regular heap algorithm” that you read about in textbooks? You tell me.
In any case, here is the code that you can run and see, empirically, that it works. I am using VC 2005.
#include <algorithm> #include <vector> #include <iostream> bool is_heap_valid(const std::vector<int> &vin) { std::vector<int> v = vin; std::make_heap(v.begin(), v.end()); return std::equal(vin.begin(), vin.end(), v.begin()); } int _tmain(int argc, _TCHAR* argv[]) { srand(0); std::vector<int> v; for (int i=0; i<100; i++) { v.push_back( rand() % 0x7fff ); } std::make_heap(v.begin(), v.end()); bool bfail = false; while( v.size() >= 2) { int n = v.size()/2; v[n] = 0x7fffffff; std::push_heap(v.begin(), v.begin()+n+1); std::pop_heap(v.begin(), v.end()); v.resize(v.size()-1); if (!is_heap_valid(v)) { std::cout << "heap is not valid" << std::endl; bfail = true; break; } } if (!bfail) std::cout << "success" << std::endl; return 0; }
But I have another problem, which is how to find out the index "n" that needs to be removed. I don’t see how to track this (I know the place on the heap) using std push_heap and std pop_heap. I think you need to write your own heap code and write an index on the heap for the object every time the object is moved to the heap. Sigh.
Craig hicks
source share