Cod sursa(job #677410)

Utilizator rootsroots1 roots Data 10 februarie 2012 09:38:34
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <fstream>
#include <string.h>

#define maxN 200001
#define maxB 524289

using namespace std;

ifstream in;
ofstream out;

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

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;

    in.open("heapuri.in");

    in>>N;

    out.open("heapuri.out");

    while(N--)
    {
        in>>cod;

        if(cod==3)
        {
            out<<v[h[1]]<<'\n';
            continue;
        }

        in>>x;

        if(cod==1)
        {
            v[++v[0]]=x;
            pushheap(v[0]);
        }
        else popheap(pos[x]);
    }

    in.close();
    out.close();

    return 0;
}