Cod sursa(job #658811)

Utilizator AnaTudorTudor Ana Maria Mihaela AnaTudor Data 9 ianuarie 2012 17:06:39
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.86 kb
#include <cstdio>
using namespace std;

int poz[200005],heap[200005],v[200005];
int N,M,dim;

int father (int nod)
{
    return nod>>1;//nod/2
}

int left_son (int nod)
{
    return nod<<1;//nod*2
}

int right_son (int nod)
{
    return (nod<<1)|1;//2*nod+1
}

void upheap (int nod)
{
    while (nod>1)
    {
        int aux,tata=father (nod);

        if (v[heap[tata]]>v[heap[nod]])
        {
            aux=heap[tata];
            heap[tata]=heap[nod];
            heap[nod]=aux;

            poz[heap[tata]]=tata;
            poz[heap[nod]]=nod;

            nod=tata;
        }
        else
            return ;
    }
}

void downheap (int nod)
{
    while (2*nod<=dim)
    {
        int aux,fiu=left_son (nod);
        if (fiu+1<=dim && v[heap[fiu+1]]<v[heap[fiu]])
            ++fiu;

        if (v[heap[fiu]]<v[heap[nod]])
        {
            aux=heap[nod];
            heap[nod]=heap[fiu];
            heap[fiu]=heap[nod];

            poz[heap[fiu]]=fiu;
            poz[heap[nod]]=nod;

            nod=fiu;
        }
        else
            return ;
    }
}

void insert (int val)
{
    v[++M]=val;

    heap[++dim]=M;
    poz[heap[dim]]=dim;
    upheap (dim);
}

void erase (int ind)
{
    v[ind]=-2000000000;
    upheap (poz[ind]);
    heap[1]=heap[dim--];
    poz[heap[1]]=1;
    downheap (1);
}

int main ()
{
    freopen ("heapuri.in","r",stdin);
    freopen ("heapuri.out","w",stdout);
    int i;


    scanf ("%d",&N);
    for (i=1; i<=N; ++i)
    {
        int tip,x;

        scanf ("%d",&tip);

        if (tip==1)

    {
            scanf ("%d",&x);
            insert (x);
        }
        if (tip==2)
        {
            scanf ("%d",&x);
            erase (x);
        }

        if (tip==3)
            printf ("%d\n",v[heap[1]]);
    }

    return 0;
}