Cod sursa(job #254008)

Utilizator runnaway90Oprescu Radu Constantin runnaway90 Data 6 februarie 2009 15:14:15
Problema Heapuri Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.15 kb
#include<stdio.h>
#define N 200000

int a[N], h[N], pos[N], lg;

void push(int x){
int aux;
    while(x/2 && a[ h[x] ] < a[ h[ x/2 ] ] ){
        aux = h[x]; h[x] = h[x/2]; h[x/2] = aux;

        pos[h[x]] = x;
        pos[h[x/2]] = x/2;

        x/=2;
    }
}

void pop(int x){
int y = 0, aux;

    while (x!=y){
        y = x;

        if (y*2 <= lg && a[h[x]] > a[h[y*2]]) x = y*2;
        if (y*2+1 <= lg && a[h[x]] > a[h[y*2+1]]) x = y*2+1;

        aux = h[x]; h[x] = h[y]; h[y] = aux;

        pos[h[x]] = x;
        pos[h[y]] = y;
    }
}



int main(){
int t, c, x, nr = 0;
    freopen("heapuri.in","r",stdin); freopen("heapuri.out","w",stdout);
    scanf("%d ",&t);
    for ( ; t ; t--){
        scanf("%d ",&c);

        if (c <= 2) scanf("%d", &x);

        if (c == 1){
            nr++;lg++; a[nr]=x; h[lg]=nr; pos[nr]=lg;
            push(lg);
        }
        else
            if (c == 2){
                h[ pos [x] ] = h[ lg ]; lg--;
                pos[h[pos[x]]] = pos[x];
                if ( lg > 1 ) pop( pos[x] );
            }
            else printf("%d\n", a[h[1]]);
    }
    return 0;
}