Cod sursa(job #674196)

Utilizator Eugen01Vasilescu Eugen Eugen01 Data 5 februarie 2012 19:33:08
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include<stdio.h>
#define Nmax 2000009

int next,N,nr,x,aux,n,i,p,t,a[Nmax],poz[Nmax],H[Nmax];

void swap(int x,int y)
{
    aux=H[x];
    H[x]=H[y];
    H[y]=aux;

    aux=poz[H[x]];
    poz[H[x]]=poz[H[y]];
    poz[H[y]]=aux;
}

void heap_up(int nod)
{
    while (a[H[nod]]<a[H[nod>>1]] && nod>1)
    {
        swap(nod,nod>>1);
        nod>>=1;
    }
}

void heap_down(int nod)
{
    while (1)
    {
        if (nod<<1 > nr) return;
        if ((nod<<1)+1 >nr || a[H[nod<<1]]<a[H[(nod<<1)+1]]) next=nod<<1;
            else next=(nod<<1)+1;
        if (a[H[nod]]<a[H[next]]) return;
            else
            {
                swap(nod,next);
                nod=next;
            }
    }
}
int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);

    scanf("%d",&n);
    for (i=1;i<=n;i++)
    {
        scanf("%d",&t);
        if (t==1)
        {
            scanf("%d",&a[++N]);
            H[++nr]=N;
            poz[N]=nr;
            heap_up(nr);
        }
        else if (t==2)
        {
            scanf("%d",&x);
            p=poz[x];
            swap(p,nr--);
            heap_down(p);
            heap_up(p);
        }
        else printf("%d\n",a[H[1]]);
    }
}