Cod sursa(job #1115824)

Utilizator Master011Dragos Martac Master011 Data 22 februarie 2014 02:22:14
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include<cstdio>
using namespace std;

const int Dmax = 200000;
int v[Dmax + 1], h[Dmax + 1], poz[Dmax + 1], nre, rr;

void change (int poz1, int poz2){
    int aux = h[poz1];
    h[poz1]=h[poz2];
    h[poz2]=aux;
    poz[h[poz1]]=poz1;
    poz[h[poz2]]=poz2;
}

void up(int f){
    while (f>1 && v[h[f]] < v[h[f/2]]){
        change(f,f/2);
        f /= 2;
    }
}

void down(int f){
    bool ok = true;
    int fs,fd,good;
    while(ok){
        fs = 2*f, fd = 2*f+1, good = f;
        if(fs <= nre && v[h[fs]] < v[h[good]])
            good = fs;
        if(fd <= nre && v[h[fd]] < v[h[good]])
            good = fd;
        if(good != f){
            change(f, good);
            f=good;
        }else{
            ok = false;
        }
    }
}

void add(int x){
    h[++nre]=x;
    poz[x]=nre;
    up(nre);
}

void f_delete(int x){
    change(x,nre--);
    up(x);
    down(x);
}

int main (){
    FILE *in = fopen ("heapuri.in","r");
    FILE *out = fopen ("heapuri.out","w");

    int Q,type,x;
    fscanf(in,"%d",&Q);

    while (Q--){
        fscanf(in,"%d",&type);
        if(type==1){
            fscanf(in,"%d",&x);
            v[++rr]=x;
            add(rr);
        }else if(type==2){
            fscanf(in,"%d",&x);
            f_delete(poz[x]);
        }else{
            fprintf(out,"%d\n",v[h[1]]);
        }
    }

    fclose(in);
    fclose(out);
    return 0;
}