【问题标题】:Can priority queue be made by using simple queues [closed]可以通过使用简单队列来制作优先级队列[关闭]
【发布时间】:2019-12-31 14:26:13
【问题描述】:
【问题讨论】:
标签:
c++
data-structures
queue
priority-queue
【解决方案1】:
priority queue 是一个抽象的数据结构,包含一些必需的操作:
- 检查是否为空(
is_empty);
- 按“优先级”插入元素 (
insert);
- 查找并删除具有最高优先级的元素 (
pop)。
有很多方法可以实现这一点,但您通常会为pop 和insert 寻找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;
}
这为insert 和pop 提供了(摊销的)O(log n) 复杂性。
【解决方案2】:
差不多。
您不能“排序”标准队列,因为它没有随机访问权限。 std::priority_queue 通常由向量支持。
它只是为您进行“自动排序”,仅此而已。您实际上不会重新排序整个事情(这会做很多毫无意义的比较):您会进行下限/上限搜索以查找插入新元素的位置。删除也可以类似的特殊化,因为你知道元素是经过排序的,所以可以进行二分搜索。
但最终结果是一个行为很像队列的东西,是的。