大根堆和小根堆
#include<iostream>
using namespace std;
int h[1000000];
int z=0;//z表示数列中有几个元素
void up(int x){
while(x>1 && h[x]<h[x/2]){
swap(h[x],h[x/2]);
x /= 2;
}
}
void down(int x){
while(x*2<=z){
int t=x*2;
if(t+1<=z && h[t+1]<h[t]) t++;
if(h[t]>=h[x]) break;
swap(h[x],h[t]);//交换
x=t;
}
}
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
int op;
cin>>op;
if(op==1){
int x;
cin>>x;
h[++z]=x;
up(z);
}
if(op==2){
cout<<h[1]<<endl;
}
if(op==3){
h[1]=h[z--];
down(1);
}
}
return 0;
}
洛谷P3378堆的模板
规律是x/2
插入为向上排序
删除为向下排序
小根堆——
up: h[x]<h[x/2]
down: h[t]>=h[x]
而大根堆——
up: h[x]>h[x/2]
down: h[t]<=h[x]
浙公网安备 33010602011771号