跳到正文

题解

题解:P3378 【模板】堆

b__b约 7 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 7 分钟
题目
P3378

版本

  1. v1当前

堆

什么是堆?

摘自百度百科:

堆(heap)是计算机科学中一类特殊的数据结构的统称。堆通常是一个可以被看做一棵树的数组对象。堆总是满足下列性质:

  • 堆中某个结点的值总是不大于或不小于其父结点的值;
  • 堆总是一棵完全二叉树。

将根结点最大的堆叫做最大堆或大根堆,根结点最小的堆叫做最小堆或小根堆。

如何实现?

下列有两种方法:手写堆与 STL 大法,以下主要讲解手写堆。

手写堆有两种操作:上浮或下沉,这里用大根堆举例,小根堆原理相近。

(下文图片来自 https://blog.csdn.net/xiaomucgwlmx/article/details/103522410)

上浮

某个节点的优先级上升,或者在堆底部加入新元素时,要从下至上恢复堆的顺序。

例如,对于下图的堆:

如果我们插入一个 1616,那么会先变成这样。

然后 1616 往上一瞅:欸,上面的 22 怎么比我小?让他滚下来!

于是我们交换 1616 与 22:

但是这样还是不够的,因为 1616 发现上面的 1010 还是比他小,所以还是需要让 1616 与 1010 交换。

于是我们得到:

这时满足了堆的性质,于是插入完成。

下沉

某个节点的优先级下降,或者弹出堆顶时,要从上到下恢复堆的顺序。

还是这个堆:

现在我们删除 1010,这时我们发现这个二叉树没有头了!

怎么办?那我们先把 11 放上去吧:

放上去之后 11 发现:不对!77 比我大!

于是 11 与 77 交换:

但是交换完后 55 又大于 11 了,因此继续交换:

于是下沉完成。

复杂度

因为堆是一个完全二叉树,因此只有 log⁡2n\log_2n 层,上浮和下沉最多只会进行 log⁡2n\log_2n 次,因此上浮和下沉的复杂度都为 O(log⁡2n)\mathcal{O}(\log_2n),如果有 mm 次插入或删除操作,复杂度为 O(mlog⁡2n)\mathcal{O}(m\log_2n)。输出最大或最小值可直接输出堆顶,复杂度为 O(1)\mathcal{O}(1)。

STL 的优先队列也是使用了堆,复杂度同理。

代码

下列给出手写堆和 STL。

手写堆
C++
#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

C++
#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();
        }
    }
}
原文