开发者

Priority queue structure used?

While searching for some functions in C++ standard library documentation I read that push and pop for priority queues needs constant time.

http://www.cplusplus.com/reference/stl/priority_queue/push/

Constant (in the priority_queue). Although notice that push_heap operates in logarithmic time.

My question is what kind of data structure is used to ma开发者_运维百科intain a priority queue with O(1) for push and pop ?


I assume you are referring to cplusplus.com's page.

Earlier on the page it says:

This member function effectively calls the member function push_back of the underlying container object, and then calls the push_heap algorithm to keep the heap property of priority_queues.

So, after the O(1) push, the data structure has lost its heap property invariant and will then always follow that with an O(log N) call to restore that property. In other words, the O(1) operation is only one part of the entire operation; the full operation is O(1) + O(log N) which is the same as O(log N).

I guess the reason they mention that is that priority queue is an adapter and they are trying to emphasize the difference between what the underlying container does vs what the adapter does.


The underlying storage for priority_queue can be a vector or a deque or anything similar that supports random access iterators. The storage is maintained as a heap, which is not O(N) for push, so I suspect you have read this wrong


Push and Pop run in Logarithmic time according to

http://www.cppreference.com/wiki/stl/priority_queue/pop

http://www.cppreference.com/wiki/stl/priority_queue/push


I'm skeptical about the O(1) claim... where did you see it?

In any case, here are some notes on gcc's implementation of a priority queue.


There is not such a kind of heap. They have written that it calls push_heap which is logarithmic so it is logn.


The standard defines those members in terms of push_heap and pop_heap, which implies the compilexity.

If what that reference says is true (it says top is also constant), why doesn't anybody implement general-purpose O(N) sorting using std::priority_queue?

On second though, this is what the reference may be trying to say, in a very misleading way: the complexity is that of push_back O(1) + push_heap (O(log N))

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜