Heapify in logarithmic time using the C++ standard library

前端 未结 4 421
灰色年华
灰色年华 2021-01-06 00:35

I have a heap using std::make_heap:

std::vector v{1,2,3,5,9,20,3};
std::make_heap(v.begin(), v.end());

now I update

4条回答
  •  无人及你
    2021-01-06 01:19

    If we look closer at your statement:

    now I disturb heap by changing one random element of heap.

    For heapifying in O(log n) you can only directly "disturb" the back or the front of the vector (which corresponds somehow to inserting or deleting an element). In these cases, (re)heapification can be then achieved by means of the std::push_heap and std::pop_heap algorithms, which take logarithmic running time.

    That is, the back:

    v.back() = 35;
    std::push_heap(v.begin(), v.end()); // heapify in O(log n)
    

    or the front:

    v.front() = 35;
    
    // places the front at the back
    std::pop_heap(v.begin(), v.end()); // O(log n)
    // v.back() is now 35, but it does not belong to the heap anymore
    
    // make the back belong to the heap again
    std::push_heap(v.begin(), v.end()); // O(log n)
    

    Otherwise you need to reheapify the whole vector with std::make_heap, which takes linear running time.


    Summary

    It's not possible to modify an arbitrary element of the heap and achieve the heapification in logarithmic running time with the standard library (i.e., the function templates std::push_heap and std::pop_heap). However, you can always implement the heap's swim and sink operations by yourself in order to heapify in logarithmic running time.

提交回复
热议问题