Does changing a priority queue element result in resorting the queue?

前端 未结 4 1563
抹茶落季
抹茶落季 2021-01-02 16:58

I have a priority_queue, and I want to modify some of it\'s contents (the priority value), will the queue be resorted then?

It depends if it resorts on push/pop (mor

4条回答
  •  清酒与你
    2021-01-02 17:23

    Unfortunately, the std::priority_queue class doesn't support the increase/decrease_key operations that you're looking for. Of course it's possible to find the element within the heap you want to update, and then call make_heap to restore the binary heap invariants, but this can't be done as efficiently as it should be with the std:: container/algorithms. Scanning the heap to find the item is O(N) and then make_heap is O(N) on top of that - it should be possible to do increase/decrease_key in O(log(N)) for binary heaps that properly support updates.

    Boost provides a set of priority queue implementations, which are potentially more efficient than the std::priority_queue (pairing heaps, Fibonacci heaps, etc) and also offer mutability, so you can efficiently perform dynamic updates. So all round, using the boost containers is potentially a much better option.

提交回复
热议问题