Cod sursa(job #677404)

Utilizator rootsroots1 roots Data 10 februarie 2012 09:26:46
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.32 kb
#include <stdio.h>
#include <string.h>

#define maxN 200001
#define maxB 524289
#define lineR 262144

int h[maxB];
int v[maxN];
int pos[maxN];

bool ok=true;
char line[lineR];
int ind=0;

inline int read()
{
    if(ok)
    {
        ok=false;
        fread(line,1,lineR,stdin);
        ind=0;
    }

    int ret=0;

    for(;'0'<=line[ind]&&line[ind]<='9';)
    {
        ret*=10;
        ret+=line[ind]-'0';
        if(++ind==lineR)
        {
            ind=0;
            fread(line,1,lineR,stdin);
        }
    }

    for(;'0'>line[ind]||line[ind]>'9';)
        if(++ind==lineR)
        {
            ind=0;
            fread(line,1,lineR,stdin);
        }

    return ret;
}

inline void heapup(int nod)
{
    int aux=h[nod];

    for(;nod>1&&v[aux]<v[h[nod>>1]];nod>>=1)
    {
        h[nod]=h[nod>>1];
        pos[h[nod]]=nod;
    }

    h[nod]=aux;
    pos[aux]=nod;
}

inline void heapdown(int nod)
{
    int L,R,aux=h[nod];

    while(1)
    {
        L=(nod<<1);
        R=L+1;

        if(R<=h[0]&&v[h[R]]<v[h[L]]&&v[h[R]]<v[aux])
        {
            h[nod]=h[R];
            pos[h[nod]]=nod;
            nod=R;
        }
        else
        if(L<=h[0]&&v[h[L]]<v[aux])
        {
            h[nod]=h[L];
            pos[h[nod]]=nod;
            nod=L;
        }
        else
        {
            h[nod]=aux;
            pos[aux]=nod;
            return;
        }
    }
}

inline void pushheap(int nod)
{
    h[++h[0]]=nod;
    pos[nod]=h[0];
    heapup(h[0]);
}

inline void popheap(int nod)
{
    if(nod==h[0])
    {
        --h[0];
        return;
    }

    h[nod]=h[h[0]];
    pos[h[nod]]=nod;
    --h[0];

    if(nod>1&&v[h[nod>>1]]>v[h[nod]]) heapup(nod);
    else heapdown(nod);
}

int main()
{
    int N,cod,x;

    freopen("heapuri.in","r",stdin);

    //N=read();
    scanf("%d",&N);

    freopen("heapuri.out","w",stdout);

    while(N--)
    {
        //cod=read();
        scanf("%d",&cod);

        if(cod==3)
        {
            printf("%d\n",h[1]);
            continue;
        }

        //x=read();
        scanf("%d",&x);

        if(cod&1)
        {
            v[++v[0]]=x;
            pushheap(v[0]);
            continue;
        }

        popheap(pos[x]);
    }

    return 0;
}