Cod sursa(job #1023015)

Utilizator alecsandrualex cuturela alecsandru Data 6 noiembrie 2013 12:06:49
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include<cstdio>
int h[200100],nh,n,i,a,N,tip;
int poz[200100],v[200100];
void schimba(int a, int b)
{
    int c,d;
    c=h[a];
    h[a]=h[b];
    h[b]=c;
    poz[v[h[a]]]=a;
    poz[v[h[b]]]=b;

}
void coboara(int p)
{
    int fs=2*p,fd=2*p+1,bun=p;
    if(fs<=nh&&v[h[fs]]<v[h[bun]])
        bun=fs;
    if(fd<=nh&&v[h[fd]]<v[h[bun]])
        bun=fd;
    if(bun!=p)
    {
        schimba(p,bun);
        coboara(bun);
    }
}
void urca(int p)
{
    while(p!=1&&v[h[p]]<v[h[p/2]])
    {
        schimba(p,p/2);
        p/=2;
    }
}
void adauga(int x)
{
    h[++nh]=n;
    poz[v[n]]=nh;
    urca(nh);
}
void sterge(int p)
{
    schimba(p,nh--);
    urca(p);
    coboara(p);
}

int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&N);
    for(i=1;i<=N;i++)
    {
        scanf("%d",&tip);
        if(tip==1)
        {
            scanf("%d",&v[++n]);
            adauga(v[n]);
        }
        else
        if(tip==2)
        {
            scanf("%d",&tip);
            sterge(poz[v[tip]]);
        }
        else
        {
            printf("%d\n",v[h[1]]);
        }
    }
    return 0;
}