Mai intai trebuie sa te autentifici.

Cod sursa(job #960147)

Utilizator cousin.batmanVaru Batman cousin.batman Data 9 iunie 2013 20:34:51
Problema Heapuri Scor 40
Compilator c Status done
Runda Arhiva educationala Marime 1.4 kb
#include<stdio.h>
#define MAXN 200002

int a[MAXN], h[MAXN], pos[MAXN], l=0, n, x, op;

void add(int p){
    h[++l] = p;
    pos[h[l]]=l;
    int m = l, tmp;
    while(m>1 && a[h[m]]<a[h[m/2]]){
        tmp = h[m];
        h[m] = h[m/2];
        h[m/2] = tmp;

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

        m/=2;
    }
}

void rem(int p){
    int m, tmp;
    p = pos[p];
    if(p==l){
        --l;
        return;
    }

    h[p] = h[l--];
    pos[h[p]]=p;

    do{
        m=p;
        if(2*p<=l && a[h[2*p]] < a[h[p]]) m = 2*p;
        if(2*p+1<=l && a[h[2*p+1]] < a[h[m]]) m = 2*p+1;

        if(m!=p){
            tmp = h[p];
            h[p] = h[m];
            h[m] = tmp;

            pos[h[p]] = p;
            pos[h[m]] = m;
        }
    }while(p!=m);
}

int main(){
    int i, na=0;
    freopen("heapuri.in", "rt", stdin);
    freopen("heapuri.out", "wt", stdout);

    scanf("%d", &n);
    for(i=0; i<n ;i++){
        scanf("%d", &op);

        if(op==1){
            scanf("%d", &a[++na]);
            add(na);
        }else if(op==2){
            scanf("%d", &x);
            rem(x);
        }else
            printf("%d\n", a[h[1]]);

        /*printf("%d %d: ", i, l);
        for(x=1; x<=l; x++) printf("%d ", a[h[x]]);
        printf("\n");
        for(x=0; x<i; x++) printf("%d ", pos[x]);
        printf("\n");
        printf("\n");*/

    }

    fclose(stdin);
    fclose(stdout);
    return 0;
}