c++ 二叉堆

二叉堆的性质

编号 性质
1 二叉堆是一棵完全二叉树
2 二叉堆的任意一个节点的优先级一定大于其两个子节点的
3 如果一个节点的下标为 x ,则其左孩子的下标为 2x ,右孩子的下标为 2x+1

操作和时间复杂度

操作 时间复杂度
插入 \(O(\log n)\)
弹出 \(O(\log n)\)
获取极值 \(O(1)\)

上表可以看出二叉堆的效率还是不错的😀

操作解析

约定

  1. 我们假设这是一个小根堆(值小的优先级高)
  2. 堆中节点的值存在 h[] 数组中
  3. h[1] 是根节点
  4. 并且这个堆长这样

获取极值

直接返回根节点的值就行了

inline int top(){return h[1];}

插入元素

假如要插入 1 这个元素
首先把它加入到堆的最后

这样不符合性质 2 ,不断与其父节点互换位置,直到满足性质为止


inline void push(int res){
    register int now=++len,nxt=len>>1;
    while(nxt){
        if(res<h[nxt]) h[now]=h[nxt],now=nxt,nxt>>=1;
	else break;
    }
    h[now]=res;
}

弹出极值

先要把根的最后一个节点调到最前来

不满足性质,不断地和其优先级高的儿子比较(避免错误)并交换,直到符合性质

inline void pop(){
    register int now=1,son=2,res=d[len--];
    while(son<=len){
	if(son<len&d[son|1]<d[son]) son|=1;
	if(d[son]<res) d[now]=d[son],now=son,son<<=1;
	else break;
    }
    d[now]=res;
}

例题

洛谷 P3378
裸的模板题,把所有的操作合在一起

#include<bits/stdc++.h>
using namespace std;
inline char nc(){
    static char buf[100000],*S=buf,*T=buf;
    return S==T&&(T=(S=buf)+fread(buf,1,100000,stdin),S==T)?EOF:*S++;
}
inline int read(){
    static char c=nc();register int f=1,x=0;
    for(;c>'9'||c<'0';c=nc()) c==45?f=-1:1;
    for(;c>'/'&&c<':';c=nc()) x=(x<<3)+(x<<1)+(c^48);
    return(x*f);
}
char fwt[100000],*ohed=fwt;
const char *otal=ohed+100000;
inline void pc(char ch){
    if(ohed==otal) fwrite(fwt,1,100000,stdout),ohed=fwt;
    *ohed++=ch;
}
inline void write(int x){
    if(x<0) pc('-'),x=-x;
    if(x>9) write(x/10);
    pc(x%10+'0');
}
int d[1000002],len=0,n,cz,num;
inline void push(int res){
    register int now=++len,nxt=len>>1;
    while(nxt){
        if(res<d[nxt]) d[now]=d[nxt],now=nxt,nxt>>=1;
        else break;
    }
    d[now]=res;
}
inline void pop(){
    register int now=1,son=2,res=d[len--];
    while(son<=len){
        if(son<len&d[son|1]<d[son]) son|=1;
        if(d[son]<res) d[now]=d[son],now=son,son<<=1;
        else break;
    }
    d[now]=res;
}
int main(){
    n=read();
    for(register int i=1;i<=n;i++){
        cz=read();
        if(cz==1) push(read());
        else if(cz==2) write(d[1]),pc('\n');
        else if(cz==3) pop();
    }
    fwrite(fwt,1,ohed-fwt,stdout);
    return 0;
}


The End

posted @ 2020-04-18 14:41  小蒟蒻laf  阅读(231)  评论(1编辑  收藏  举报