Cod sursa(job #358272)

Utilizator eudanipEugenie Daniel Posdarascu eudanip Data 22 octombrie 2009 14:41:45
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
#include <stdio.h>

typedef struct { int x, key; } nod;

int M,nr,N;
nod heap[200024];
int poz[200024];

void percolate(int n)
{
    nod aux;
    for(n=N;n>1;n/=2)
        if(heap[n].key < heap[n/2].key)
        {
            aux=heap[n];
            heap[n]=heap[n/2];
            heap[n/2]=aux;

            poz[heap[n].x] = n;
            poz[heap[n/2].x] = n/2;
        }
        else
            return;
}

void sift(int n)
{
    for (;n*2<=N;)
    {
        int imin=2*n;
        if(n*2+1<=N && heap[2*n+1].key<heap[2*n].key)
            imin=2*n+1;

        if (heap[n].key<=heap[imin].key)
            return ;

        nod aux=heap[n];
        heap[n]=heap[imin];
        heap[imin]=aux;

        poz[heap[n].x] = n;
        poz[heap[imin].x] = imin;
        
        n=imin;
    }
}

void insereaza(int valoare)
{
    ++N; heap[N].key = valoare; heap[N].x = (++nr);
    poz[nr] = N;
    percolate(N);
}

void stergere(int n)
{
    poz[heap[n].x] = -1;
    poz[heap[N].x] = n;
    heap[n]=heap[N];    
    --N;
    if(n > 1 && heap[n].key<heap[n/2].key)
        percolate(n);
    else
        sift(n);
}

int main()
{
    int i,tip,x,nod;

    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&M);
    for(i=1;i<=M;++i)
    {
        scanf("%d",&tip);
        if (tip==1)
        {
            scanf("%d",&x);
            insereaza(x);
        }
        else
            if(tip==2)
            {
                scanf("%d",&x);
                stergere(poz[x]);
            }
            else
                if(tip==3)
                    printf("%d\n",heap[1].key);
    }
    return 0;
}