【问题标题】:Can priority queue be made by using simple queues [closed]可以通过使用简单队列来制作优先级队列[关闭]
【发布时间】:2019-12-31 14:26:13
【问题描述】:

优先级队列只是一个排序队列吗?可以通过创建一个简单的队列然后对其进行排序来实现吗? https://www.quora.com/What-is-the-difference-between-a-priority-queue-and-a-queue?share=1 我找到了这个链接,它指出可以通过 在插入时重新排列队列,并将最近插入的对象放在适当的优先级位置来制作优先级队列时间>。我想确定这一点,因为我的一些同行表示这是不可能的,但是如果我们创建一个坚持优先级的队列,它不会使队列成为优先级队列吗?

【问题讨论】:

标签: c++ data-structures queue priority-queue


【解决方案1】:

priority queue 是一个抽象的数据结构,包含一些必需的操作:

  • 检查是否为空(is_empty);
  • 按“优先级”插入元素 (insert);
  • 查找并删除具有最高优先级的元素 (pop)。

有很多方法可以实现这一点,但您通常会为popinsert 寻找O(log n)(摊销)复杂度。

queue 是一个抽象的数据结构,你在后面插入,在前面删除,所以它不能用于实现优先级队列(没有“排序”,除了先进先出)。

实现优先级队列的最简单方法通常是使用binary heap。使用std::vector<int> 作为后端和标准库中定义的heap operations 的极简C++ 实现可以是:

#include <algorithm>
#include <vector>

using priority_queue = std::vector<int>;

bool is_empty(priority_queue const& q) { return q.empty(); }

void insert(priority_queue &q, int value) { 
    q.push_back(value);
    std::push_heap(std::begin(q), std::end(q));
}

int pop(priority_queue &q) {
    std::pop_heap(std::begin(q), std::end(q));
    const int value = q.back();
    q.pop_back();
    return value;
}

这为insertpop 提供了(摊销的)O(log n) 复杂性。

【讨论】:

    【解决方案2】:

    差不多。

    您不能“排序”标准队列,因为它没有随机访问权限。 std::priority_queue 通常由向量支持。

    它只是为您进行“自动排序”,仅此而已。您实际上不会重新排序整个事情(这会做很多毫无意义的比较):您会进行下限/上限搜索以查找插入新元素的位置。删除也可以类似的特殊化,因为你知道元素是经过排序的,所以可以进行二分搜索。

    但最终结果是一个行为很像队列的东西,是的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-20
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      相关资源
      最近更新 更多