Cod sursa(job #1242036)

Utilizator horatiu11Ilie Ovidiu Horatiu horatiu11 Data 13 octombrie 2014 21:52:44
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
//horatiu11
# include <cstdio>
# include <algorithm>
using namespace std;
int m,op,x,n,ok,N;
int H[200001],Pos[200001],Elem[200001];
int father(int k)
{return k/2;}
inline int left_son(int k)
{return k*2;}
inline int right_son(int k)
{return k*2+1;}
void sift(int k)
{
    int son;
    do{
        son = 0;
        if (left_son(k)<=n)
        {
            son=left_son(k);
            if (right_son(k)<=n && H[right_son(k)]<H[left_son(k)])
                son=right_son(k);
            if (H[son]>=H[k])
                son=0;
        }
        if(son)
        {
            swap(H[k],H[son]);
            swap(Elem[Pos[k]],Elem[Pos[son]]);
            swap(Pos[k],Pos[son]);
            k=son;
        }
    }while(son);
}
void percolate(int k)
{
    int key=H[k],val;
    if(ok)val=N;
    else val=Pos[k];
    while(k>1 && key<H[father(k)])
    {
        H[k]=H[father(k)];
        Elem[Pos[father(k)]]=k;
        Pos[k]=Pos[father(k)];
        k=father(k);
    }
    Elem[val]=k;
    Pos[k]=val;
    H[k]=key;
}
void erase(int k)
{
    H[k]=H[n];
    --n;
    if ((k > 1) && (H[k] < H[father(k)]))
        percolate(k);
    else
        sift(k);
}
void insert(int x)
{
    H[++n]=x;
    percolate(n);
}
int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&m);
    while(m>0)
    {
        scanf("%d",&op);
        switch(op)
        {
            case 1:
                scanf("%d",&x);
                ++N;ok=1;
                insert(x);
                break;
            case 2:
                scanf("%d",&x);
                x=Elem[x];ok=0;
                erase(x);
                break;
            case 3:
                printf("%d\n",H[1]);
                break;
        }
        --m;
    }
    return 0;
}