Cod sursa(job #735906)

Utilizator vendettaSalajan Razvan vendetta Data 17 aprilie 2012 14:53:23
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include <fstream>
#include <iostream>
#define nmax 200005

using namespace std;

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

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]]) nod_min = nod*2;
        if (nod*2+1 <= n_heap && v[h[nod*2+1]] < v[h[nod]]) nod_min = nod*2+1;
        if (nod_min == nod) break;
        swap(poz[h[nod]], poz[h[nod_min]]);
        swap(h[nod], h[nod_min]);
        /*
        int aux = h[nod];
        h[nod] = h[nod_min];
        h[nod_min] = aux;
        aux = poz[h[nod]];
        poz[h[nod]] = poz[h[nod_min]];
        poz[h[nod_min]] = aux;
        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]);
            /*
            int aux = h[nod];
            h[nod] = h[nod/2];
            h[nod/2] = aux;
            aux = poz[h[nod]];
            poz[h[nod]] = poz[h[nod/2]];
            poz[h[nod/2]] = aux;
            */
            nod = nod/2;
            continue;
        }
        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]] = nod;
    h[nod] = h[n_heap];
    nod = poz[h[nod]];
    --n_heap;

    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, y;
        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";
        }

    }

}