gpt4 book ai didi

c++ - 使用什么类型的堆以及 c++ 中 std::priority_queue 的时间复杂度?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:30:12 29 4
gpt4 key购买 nike

<分区>

我想知道什么

我想问一下下面两个问题。

  • C++ 中的 std::priority_queue 使用什么类型的堆?
  • C++ 中 std::priority_queue 的 top(), pop(), push() 操作的时间复杂度是多少?

我在网上查了,没找到答案。
请告诉我答案。如果您不知道 C++ 中的所有版本,请告诉我 GCC C++11 或 C++14 的答案。

我为什么需要

我想实现 Dijkstra's Algorithm对于最短路径问题。

令图中的顶点数= |V|,边数= |E|
使用 Binary Heap 的时间复杂度为 O(|E| log |V|) .
但是时间复杂度是 O(|E| + |V| log |V|) 使用 Fibonacci Heap .

如您所见,如果图很密集,时间会非常不同。
其实有O(|V|^2)算法不用堆,所以我也想知道要不要实现。

我的实现

这是我使用 Binary Heap 实现的优先级队列.
insert(x) 等于push(x)extract() 等于top() --> pop ().
但是 std::priority_queue 比我的实现要快得多。

#include <vector>
#include <algorithm>
using namespace std;
template<class T> class PriorityQueue {
private:
    size_t size_; vector<T> heap;
public:
    PriorityQueue() : size_(1), heap(vector<T>(1, 0)) {};
    PriorityQueue(PriorityQueue& que) : size_(que.size_), heap(que.heap) {};
    size_t size() { return size_ - 1; }
    inline void insert(int x) {
        unsigned ptr = size_++; heap.push_back(x);
        while (ptr > 1) {
            if (heap[ptr >> 1] < heap[ptr]) swap(heap[ptr], heap[ptr >> 1]);
            ptr >>= 1;
        }
    }
    inline int extract() {
        int ret = heap[1]; unsigned ptr = 1;
        while ((ptr << 1) + 1 < size_) {
            ptr <<= 1;
            if (heap[ptr] > heap[ptr + 1]) swap(heap[ptr >> 1], heap[ptr]);
            else swap(heap[ptr + 1], heap[ptr >> 1]), ptr++;
        }
        heap[ptr] = heap[--size_], heap[size_] = 0;
        while (ptr > 1) {
            if (heap[ptr >> 1] < heap[ptr]) swap(heap[ptr], heap[ptr >> 1]);
            ptr >>= 1;
        }
        heap.pop_back();
        return ret;
    }
};

编辑:这不是 this question 的拷贝.只有时间复杂度。我还想知道使用的是什么类型的堆。请简单的告诉我。

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com