Cod sursa(job #1773477)

Utilizator radu_cebotariRadu Cebotari radu_cebotari Data 7 octombrie 2016 21:26:58
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include<fstream>
#include<iostream>
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");
const int NMAX = 300000;

struct hp{
    int val,poz;
};
hp h[NMAX+2];

int n,poz[NMAX+2],el,elem;

int tata(int nod)
{

    return nod/2;
}

int fiu_st(int nod)
{

    return nod*2;
}

int fiu_dr(int nod)
{

    return nod*2+1;
}

void sift(int nod,int N)
{

    int son;
    do{

        son = 0;
        if(fiu_st(nod) <= N)
            son = fiu_st(nod);
        if(h[fiu_dr(nod)].val < h[fiu_st(nod)].val && fiu_dr(nod) <= N)
                son = fiu_dr(nod);
        if(h[nod].val < h[son].val)
            son = 0;
        if(son != 0)
        {

            swap(h[nod].val,h[son].val);
            swap(h[nod].poz,h[son].poz);
            poz[h[nod].poz] = nod;
            poz[h[son].poz] = son;
        }
    }while(son);
}

void perc(int nod)
{

    while(tata(nod) >= 1 && h[tata(nod)].val > h[nod].val)
    {
        swap(h[nod].val,h[tata(nod)].val);
        swap(h[nod].poz,h[tata(nod)].poz);
        poz[h[nod].poz] = nod;
        poz[h[tata(nod)].poz] = tata(nod);
        nod = tata(nod);
    }
}

void del(int pz,int& N)
{

    h[pz].val = h[N].val;
    h[pz].poz = h[N].poz;
    N--;
    sift(pz,N);
    perc(pz);
}

int minim()
{

    return h[1].val;
}

int main()
{

    in>>n;
    int Q,x;
    for(int i = 1 ; i <= n ; i++){

        in>>Q;
        if(Q == 1){
            in>>x;
            ++el;
            ++elem;
            h[el].val = x;
            h[el].poz = elem;
            poz[elem] = el;
            perc(el);
        }
        else if(Q == 2){
            in>>x;
            del(poz[x],el);
        }
        else
            out<<minim()<<"\n";
    }
    return 0;
}