5

Lets say I am writing Dijkstra's Algorithm, and I have a priority queue that is keeping the shortest distance node on the top. However as I traverse the graph I will be updating the distance to that vertex. I have placed references to all vertices in the priority queue that are contained in the data structure. Now as I update the vertices in the data structure, I would like for the data in the priority queue to adapt to those changes, so the nearest node is always on top. However, after stepping through my application with the debugger, I have noticed that the priority queue does not update itself. How do I get it to do this, without re-inserting all vertices back into it?

Matthew Hoggan
  • 7,402
  • 16
  • 75
  • 140

1 Answers1

4

STL priority_queue assumes that you only use the push() and pop() methods to modify the data structure. It does not track changes to the data structure.

After modifying the interior of the priority_queue's underlying container you need to call make_heap() on the container to restore the heap property. STL priority_queue does not provide iterators on the underlying container. Instead you need to manually manage a deque or a vector as a priority queue and call make_heap(), push_heap(), and pop_heap() as needed.

MtnViewJohn
  • 683
  • 4
  • 9
  • 1
    Either this or write your own implementation, since you know what items changed, and make_heap() does not. – Nathan S. Apr 09 '12 at 05:26
  • @MtnViewJohn do you have a working sample? Or a snip-bit of code? Don't need full thing just a very small example – Matthew Hoggan Apr 09 '12 at 05:27
  • Here is a [link][1] to SGI's implementation of priority_queue. You could copy this and extend it to include a fix-up method that calls make_heap() to fix the heap after to change its contents. @NathanS suggestion is also very good: as you modify each node immediately perform the necessary heap rotate operations to maintain the heap property. [1] http://www.sgi.com/tech/stl/stl_queue.h – MtnViewJohn Apr 09 '12 at 05:43
  • 4
    Although calling make_heap() does restore the heap property, it runs in O(n) time. A proper implementation of the heap update should run in O(lg n) time -- this is the reheapify function found in algorithm textbooks like Cormen, et al. Obviously, if n is large and/or you are updating the priorities often, then the difference in running time will be palpable. I found an implementation that does do reheapify in logarithmic time: http://blog.smellthedata.com/2009/08/mutable-heaps-in-c-for-updates-to.html – stackoverflowuser2010 Jul 08 '12 at 17:43