Cod sursa(job #1988957)

Utilizator victoreVictor Popa victore Data 5 iunie 2017 13:12:56
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include<cstdio>

const int nmax=200005;

int heap[nmax],last,pos[nmax],cnt,a[nmax];

inline void swapum(int a,int b)
{
    heap[a]^=heap[b];
    heap[b]=heap[a]^heap[b];
    heap[a]^=heap[b];
    pos[heap[a]]=a;
    pos[heap[b]]=b;
}


inline void urca(int x)
{
    int temp=x;
    while(temp/2&&a[heap[temp/2]]>a[heap[temp]])
    {
        swapum(temp,temp/2);
        temp/=2;
    }
}

inline void coboara(int x)
{
    int temp=x;
    if(2*temp<=last&&a[heap[2*temp]]<a[heap[temp]])
    {
        swapum(temp,2*temp);
        coboara(2*temp);
    }
    else if(2*temp+1<=last&&a[heap[2*temp+1]]<a[heap[temp]])
    {
        swapum(temp,2*temp+1);
        coboara(2*temp+1);
    }
}
inline int push(int number)
{
    a[++cnt]=number;
    heap[++last]=cnt;
    pos[cnt]=last;
    urca(last);
}


int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    int n,i,op,nr,xus;
    scanf("%d",&n);
    for(i=1;i<=n;++i)
    {
        scanf("%d",&op);
        if(op==3)
            printf("%d\n",a[heap[1]]);
        else if(op==1)
        {
            scanf("%d",&nr);
            push(nr);
        }
        else
        {
            scanf("%d",&nr);
            xus=pos[nr];
            swapum(pos[nr],last);
            --last;
            coboara(xus);
        }
    }
}