1、B站视频链接:A15 堆 堆排序_哔哩哔哩_bilibili
题目链接:【模板】堆 - 洛谷
#include <iostream>
using namespace std;
int a[1000010],cnt;
void up(int u){ //上浮
if(u/2 && a[u/2]>a[u])
swap(a[u],a[u/2]), up(u/2);
}
void down(int u){ //下沉
int v=u;
if(u*2<=cnt && a[u*2]<a[v]) v=u*2;
if(u*2+1<=cnt && a[u*2+1]<a[v]) v=u*2+1;
if(u!=v) swap(a[u],a[v]), down(v);
}
void push(int x){ //压入
a[++cnt]=x;
up(cnt);
}
void pop(){ //删除
a[1]=a[cnt--];
down(1);
}
int main(){
int n; scanf("%d",&n); //操作次数
while(n--){
int op,x; scanf("%d",&op);
if(op==1) scanf("%d",&x), push(x);
else if(op==2) printf("%d\n",a[1]);
else pop();
}
return 0;
}
2、STL大法好
#include <bits/stdc++.h>
using namespace std;
priority_queue<int,vector<int>,greater<int>> q;
//小根堆
int main(){
int n;
cin>>n;
while(n--){
int op,x;
cin>>op;
if(op==1){
cin>>x;
q.push(x);
}else if(op==2){
cout<<q.top()<<endl;
}else{
q.pop();
}
}
return 0;
}