[银河AIの模板计划之数据结构] 二叉堆(优先队列)
前言
堆可不止这一种(
但不得不说还挺好用
介绍
堆实际上可以看做一个保持单调性的树。
有两种方式实现堆:
这里主要介绍手写堆(增加,删除,查询操作)。
-
1.增加操作
在堆尾添加一个数,不断比较这个数的父节点和其本身的大小,如果该不满足单调性,则交换。
反复操作即可。
-
2.删除操作
将堆尾的数移动到堆首,比较其子节点,如果不满足单调性,则交换。
本操作实际上相当于是增加操作的逆过程。
-
3.查找操作
printf("%d ",pq[1]);
时间复杂度
代码实现
(以P3378为例小根堆())
手写堆:
#include<cstdio>
#include<algorithm>
#define pq priority_queue
#define pq_push(x) add(x)
#define pq_pop() del()
#define pq_top() pq[1]
using namespace std;
const int N=1e6+1;
int n,opt,l;
int priority_queue[N];
inline void add(int x){
pq[++l]=x;int s=l,next;
while(s>1){
next=s/2;
if(pq[next]>pq[s]) swap(pq[s/2],pq[s]),s=next;
else return ;
}
}
inline void del(){
pq[1]=pq[l];l--;
int s=1;
while(s*2<=l&&s){
int trap=0,next=s*2;
if(next+1<=l&&pq[next+1]<pq[next]) next++;
if(pq[next]<pq[s]) trap=1,swap(pq[next],pq[s]);
if(!trap) return ;
s=next;
}
}
int x;
int main(){
scanf("%d",&n);
while(n--){
scanf("%d",&opt);
if(opt==1) scanf("%d",&x),pq_push(x);
if(opt==2) printf("%d\n",pq_top());
if(opt==3) pq_pop();
}
}