1. 程式人生 > >手寫的堆

手寫的堆

line span main color break for add == else

#include<bits/stdc++.h>
using namespace std;
int tot,dui[10000000],n,x,y;

inline void add(int i)
{
    tot++;
    dui[tot] = i;
    int k = tot;
    while(k>1 && dui[k] < dui[k>>1])
    {
        swap(dui[k] , dui[k>>1]);
        k >>= 1;
    }
}

inline void del()
{
    dui[
1] = dui[tot--]; int p = 1; bool k = 0; while(p * 2 <= tot) { if(p * 2 == tot) k = 0; else k = dui[p*2] > dui[p*2+1]; if(dui[p] > dui[p * 2 + (int)k]) { swap(dui[p] , dui[p * 2 + (int)k]); p = p * 2 + (int)k; }
else break; } } int main(){ scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&x); if(x==1) { scanf("%d",&y); add(y); } if(x==2) printf("%d\n",dui[1]); if(x==3) del(); } }

手寫的堆