Cod sursa(job #735932)

Utilizator vendettaSalajan Razvan vendetta Data 17 aprilie 2012 16:00:53
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>
#include <iostream>
#define nmax 200005

using namespace std;

int m, poz[nmax], h[nmax], v[nmax], n_heap=0, n=0;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

void in_jos(int nod){

    for(int ok=1; ok; ){
        int nod_min = nod;
        if (nod*2 <= n_heap && v[h[nod*2]] < v[h[nod_min]]) nod_min = nod*2;
        if (nod*2+1 <= n_heap && v[h[nod*2+1]] < v[h[nod_min]]) nod_min = nod*2+1;
        if (nod_min == nod) break;
        swap(poz[h[nod]], poz[h[nod_min]]);
        swap(h[nod], h[nod_min]);
        nod=nod_min;
    }

}

void in_sus(int nod){

    for(; nod!=1; ){
        if (nod > 1 && v[h[nod]] < v[h[nod/2]]){
            swap(poz[h[nod]], poz[h[nod/2]]);
            swap(h[nod], h[nod/2]);
            nod = nod/2;
        } else nod = 1;
    }

}

void adauga(int val){

    h[++n_heap] = ++n;
    poz[n] = n_heap;
    v[n] = val;
    in_sus(n_heap);

}

void sterge(int nod){

    poz[h[n_heap]] = poz[h[nod]];
    h[nod] = h[n_heap];
    --n_heap;
    nod = poz[h[nod]];
    if (nod > 1 && v[h[nod]] < v[h[nod/2]])
        in_sus(nod);
    else in_jos(nod);

}

int main(){

    f >> m;

    for(int i=1; i<=m; i++){
        int tip, x;
        f >> tip;
        if (tip == 1){
            f >> x;
            adauga(x);
        }else if(tip == 2){
            f >> x;
            sterge(poz[x]);
        }else if(tip == 3){
            g << v[h[1]] << "\n";
        }

    }

}