【模板】二叉堆

代码如下

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;

inline int read(){
	int x=0,f=1;char ch;
	do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
	do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
	return f*x;
}

int h[maxn],n,q;

void up(int x){
	while(x>1){
		if(h[x>>1]>h[x]){
			swap(h[x>>1],h[x]);
			x>>=1;
		}else break;
	}
}

void down(int x){
	int s=x<<1;
	while(s<=n){
		if(s<n&&h[s+1]<h[s])++s;
		if(h[x]>h[s]){
			swap(h[x],h[s]);
			x=s,s=x<<1;
		}else break;
	}
}

void insert(int val){
	h[++n]=val;
	up(n);
}

void rmv(int val){
	h[1]=h[n--];
	down(1);
}

int main(){
	q=read();
	while(q--){//1:插入元素   2:输出堆顶元素值   3:删除堆顶元素
		int opt=read();
		if(opt==1){
			int val=read();
			insert(val);
		}else if(opt==2){
			printf("%d
",h[1]);
		}else rmv(1);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/wzj-xhjbk/p/9873999.html