[银河AIの模板计划之数据结构] 二叉堆(优先队列)

· · 个人记录

update->2021.3.23

前言

堆可不止这一种(

但不得不说还挺好用

介绍

堆实际上可以看做一个保持单调性的树。

有两种方式实现堆:STL 和手写堆。

这里主要介绍手写堆(增加,删除,查询操作)。

    printf("%d ",pq[1]);

时间复杂度 O(n\log n)

代码实现

(以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();
    }
}
```cpp #include<bits/stdc++.h> #include<queue> using namespace std; int n,x,opt; priority_queue<int,vector<int>,greater<int> > pq; 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(); } } ``` 注:大根堆的 $STL$ 为 ```cpp priority_queue<int,vector<int>,less<int> > pq; ```