题解:P3378 【模板】堆
堆
什么是堆?
摘自百度百科:
堆(heap)是计算机科学中一类特殊的数据结构的统称。堆通常是一个可以被看做一棵树的数组对象。堆总是满足下列性质:
- 堆中某个结点的值总是不大于或不小于其父结点的值;
- 堆总是一棵完全二叉树。
将根结点最大的堆叫做最大堆或大根堆,根结点最小的堆叫做最小堆或小根堆。
如何实现?
下列有两种方法:手写堆与 STL 大法,以下主要讲解手写堆。
手写堆有两种操作:上浮或下沉,这里用大根堆举例,小根堆原理相近。
(下文图片来自 https://blog.csdn.net/xiaomucgwlmx/article/details/103522410)
上浮
某个节点的优先级上升,或者在堆底部加入新元素时,要从下至上恢复堆的顺序。
例如,对于下图的堆:
如果我们插入一个
然后
于是我们交换
但是这样还是不够的,因为
于是我们得到:
这时满足了堆的性质,于是插入完成。
下沉
某个节点的优先级下降,或者弹出堆顶时,要从上到下恢复堆的顺序。
还是这个堆:
现在我们删除
怎么办?那我们先把
放上去之后
于是
但是交换完后
于是下沉完成。
复杂度
因为堆是一个完全二叉树,因此只有
STL 的优先队列也是使用了堆,复杂度同理。
代码
下列给出手写堆和 STL。
手写堆
#include <iostream>
#include <cctype>
int heap[1000005], len; //满二叉树
//这种表示方法中,满二叉树中第i个节点的左儿子和右儿子分别为i*2和i*2+1
int main() {
int n, now;
char ch;
for (scanf("%d", &n); n--;) {
for (; !isdigit(ch = getchar()););
switch (ch) {
case '1':
scanf("%d", heap + (now = ++len));
while (now) { //上浮
int up = now >> 1;
if (heap[up] > heap[now]) std::swap(heap[up], heap[now]);
else break;
now = up;
}
break;
case '2':
printf("%d\n", heap[1]);
break;
case '3':
std::swap(heap[len--], heap[now = 1]);
while ((now << 1) <= len) { //下沉
int low = now << 1;
if (low + 1 <= len && heap[low] > heap[low + 1]) ++low;
if (heap[low] < heap[now]) std::swap(heap[now], heap[low]);
else break;
now = low;
}
}
}
}
STL
下文不介绍 priority_queue,若有了解兴趣可看 https://cppreference.cn/w/cpp/container/priority_queue
#include <cstdio>
#include <cctype>
#include <vector>
#include <queue>
int main() {
std::priority_queue<int, std::vector<int>, std::greater<int>> q; //小根堆
int n, x;
char ch;
for (scanf("%d", &n); n--;) {
for (; !isdigit(ch = getchar()););
switch (ch) {
case '1':
scanf("%d", &x);
q.push(x);
break;
case '2':
printf("%d\n", q.top());
break;
case '3':
q.pop();
}
}
}