P3378 【模板】堆 题解

· · 题解

简介

堆一种维护极值的数据结构,有 STL 和手写两种版本,本文主要讲手写板。

比较模拟堆和 STL 的优先队列

模拟堆 优先队列
相同点 可以维护极值 可以维护极值
不同点 1 可以在任意位置随意插入或删除一个元素 只能在堆顶添加或删除元素
不同点 2 可以查找第 k 大的元素 只能查询堆顶
不同点 3 可以查找第 k 个元素是第几大 只能查询堆顶
不同点 4 快 慢

简而言之,优先队列 priority_queue 能干的事模拟堆都能干,但模拟堆能干的事优先队列不一定能干,而且模拟堆更快。不过优先队列也不是一无是处,它凭借代码短,不易出错(因为是 STL 自带的),深受人们的青睐。在大部分题目中,用优先队列就足够了,如堆优化的 dijkstra 算法。

前置

  1. 按位左移 << ,等同乘上 2 的几次方, x << k 等同于 x×2^k ,如 x << 1 等同于 x×2 。
  2. 按位右移 >> ,等同乘上 2 的几次方, x >> k 等同于 x÷2^k ,如 x >> 1 等同于 x÷2 。
  3. 按位或 | , x >> 1 | 1 等同于 x×2+1 。

简单模拟堆实现

模板题1(AcWing.838)

输入一个长度为 n 的整数数列,从小到大输出前 m 小的数。

思路

模拟堆可以实现的操作:

  1. 插入一个数 x
  2. 输出当前集合中的极值
  3. 删除当前集合中的极值
  4. 删除修改第 k 个插入的数

在本题中,仅需考虑前三个操作,也就是优先队列能实现的操作,可以看做一个堆排序。

下图演绎了堆排序的过程。

可以发现,再排序的过程中,每插入一个元素,就先把它放到堆顶,然后与它的子节点比较,如果比子节点大(从小到大排序),就交换它和它的子节点,然后重复这个过程。这个就是 down() 操作,复杂度 O(\operatorname{log}n) ,用递归实现。

那如何建出堆呢?

这里有一种神奇的建堆方式(好像也不怎么神奇),就是用数组建堆。 具体地说,用 a 数组存储堆,则:

这种存储方式初看好像有点不靠谱,似乎会有重复,实则不然。

下图说明了数组如何存储堆(原创图):

代码

#include <bits/stdc++.h>
#define ll long long
#define rll register ll
#define cll const ll
#define N 100005
using namespace std;
inline ll read()
{
    rll x=0;bool f=1;register char c=getchar();
    while(c<48||c>57){if(c=='-') f=0;c=getchar();}
    while(c>=48&&c<=57){x=x*10+(c^48);c=getchar();}
    return f?x:-x;
}
inline void write(ll x)
{
    if(x<0) putchar('-'),x=-x;
    if(x>9) write(x/10);
    putchar(x%10+48);
}//卡常
cll n=read();
ll m=read(),len=n,a[N];//len 代表堆内元素个数
inline void down(ll u)
{
    ll t=u;
    if((u<<1)<=len&&a[u<<1]<a[t]) t=u<<1;
    if((u<<1|1)<=len&&a[u<<1|1]<a[t]) t=u<<1|1;
    if(u!=t) swap(a[u],a[t]),down(t);
}//比子节点大则往下掉
int main()
{
    for(rll i=1;i<=n;i++) a[i]=read();//读入时直接读入即可(反正是无序的)
    for(rll i=(n>>1);i;i--) down(i);//对每个点进行 down() 操作,仅需操作一半的元素
    while(m--)
    {
        write(a[1]),putchar(' ');
        a[1]=a[len--],down(1);
        //为了方便,每次输出堆顶后用堆尾替换堆顶,再跑一遍 down()
    }
    return 0;
}

复杂模拟堆

模板题2(AcWing.839)

维护一个集合,初始时集合为空,支持如下几种操作:

  1. I x ,插入一个数 x
  2. PM ,输出当前集合中的最小值
  3. DM ,删除当前集合中的最小值(数据保证此时的最小值唯一)
  4. D k ,删除第 k 个插入的数
  5. C k x ,修改第 k 个插入的数,将其变为 x

思路

上一题完成了前三个操作,本题将完成所有五个操作。

本题需要维护一些元素:

这样一来,每次交换堆的节点就得交换三个数组 ph 、 hp 和 a 的元素。

代码

#include <bits/stdc++.h>
#define ll long long
#define rll register ll
#define cll const ll
#define N 100005
using namespace std;
inline ll read()
{
    rll x=0;bool f=1;register char c=getchar();
    while(c<48||c>57){if(c=='-') f=0;c=getchar();}
    while(c>=48&&c<=57){x=x*10+(c^48);c=getchar();}
    return f?x:-x;
}
inline void write(ll x)
{
    if(x<0) putchar('-'),x=-x;
    if(x>9) write(x/10);
    putchar(x%10+48);
}//卡常
ll n=read(),m,len,a[N],ph[N],hp[N];
inline void heap_swap(ll x,ll y)
{
    swap(ph[hp[x]],ph[hp[y]]);//ph 以 hp 的元素值为下标
    swap(hp[x],hp[y]);
    swap(a[x],a[y]);
}//交换 a、ph、hp 的元素
inline void down(ll u)
{
    ll t=u;
    if((u<<1)<=len&&a[u<<1]<a[t]) t=u<<1;
    if((u<<1|1)<=len&&a[u<<1|1]<a[t]) t=u<<1|1;
    if(u!=t) heap_swap(u,t),down(t);
}//比子节点大则往下掉
inline void up(ll u)
{
    while((u>>1)&&a[u>>1]>a[u])
    {
        heap_swap(u>>1,u);
        up(u>>1);
    }
}//如果比父节点小则往上移
int main()
{
    while(n--)
    {
        string op;cin >> op;//用 string + cin 比较方便
        if(op=="I")
        {
            cll x=read();
            a[++len]=x;//插入在堆尾
            ph[++m]=len,hp[len]=m;//更新 ph 和 hp,它们互相依赖
            up(len);//如果比父节点小则往上移
        }//插入
        else if(op=="PM") write(a[1]),putchar('\n');//查询堆顶
        else if(op=="DM") heap_swap(1,len--),down(1);//删除堆顶
        else if(op=="D")
        {
            cll k=read(),x=ph[k];//x 保存当前被删除结点的下标
            heap_swap(x,len--);//交换堆顶和堆尾,删除堆尾
            up(x),down(x);
        }//删除第 k 个插入的数
        else if(op=="C")
        {
            cll k=read(),x=read();
            a[ph[k]]=x;
            down(ph[k]),up(ph[k]);
            //这两个操作只有一个会被执行,如果比父节点小则往上移,比子节点大则往下掉
        }//修改第 k 个插入的数为 x
    }
    return 0;
}

本题

前面原理都讲得差不多了,直接上代码。

#include <bits/stdc++.h>
#define ll long long
#define rll register ll
#define cll const ll
#define N 1000005
using namespace std;
inline ll read()
{
    rll x=0;bool f=1;register char c=getchar();
    while(c<48||c>57){if(c=='-') f=0;c=getchar();}
    while(c>=48&&c<=57){x=x*10+(c^48);c=getchar();}
    return f?x:-x;
}
inline void write(ll x)
{
    if(x<0) putchar('-'),x=-x;
    if(x>9) write(x/10);
    putchar(x%10+48);
}
ll n=read(),x,op,len,heap[N];
inline void down(ll u)
{
    rll t=u;
    if((u<<1)<=len&&heap[u<<1]<heap[t]) t=u<<1;
    if((u<<1|1)<=len&&heap[u<<1|1]<heap[t]) t=u<<1|1;
    if(u!=t) swap(heap[u],heap[t]),down(t);
}
inline void up(ll u)
{
    while((u>>1)&&heap[u>>1]>heap[u])
    {
        swap(heap[u>>1],heap[u]);
        u>>=1;
    }
}
int main()
{
    while(n--)
    {
        op=read();
        if(op==1) heap[++len]=read(),up(len);
        else if(op==2) write(heap[1]),putchar('\n');
        else swap(heap[1],heap[len--]),down(1);
    }
    return 0;
}