44pts悬关求助
查看原帖
44pts悬关求助
1368189
znzryb楼主2024/9/12 23:26

手写堆

#include <iostream>
using namespace std;
const int maxn=1e6+10;
int heap[maxn],n,op,x,hiz;
void push(int x) {
    int now=hiz+1;
    heap[now]=x;
    int fa=now>>1;
    while(heap[fa]>x) {
        heap[now]=heap[fa];
        heap[fa]=x;
        fa=fa>>1;
        now=now>>1;
    }
}
void pop() {
    if(hiz==0)
        return;
    swap(heap[1],heap[hiz]);
    int now=1,nxt=2;
    while(heap[now]>heap[nxt] && nxt+1<hiz) {
        if(heap[nxt]<=heap[nxt+1]) {
            swap(heap[now],heap[nxt]);
            now=nxt;
        }else {
            swap(heap[now],heap[nxt+1]);
            now=nxt+1;
        }
        nxt=now<<1;
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);cout.tie(nullptr);
    cin>>n;
    for(int i=1;i<=n;i++) {
        cin>>op;
        if(op==1) {
            cin>>x;
            push(x),hiz++;
        }else if(op==2) {
            cout<<heap[1]<<endl;
        }else {
            pop();
            hiz--;
        }
    }
    return 0;
}
2024/9/12 23:26
加载中...