Cod sursa(job #1526343)

Utilizator valentinpielePiele Valentin valentinpiele Data 16 noiembrie 2015 09:42:43
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
using namespace std;

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

const int Nmax = 200001;
int N, tip, x;
int v[Nmax], h[Nmax], p[Nmax];
int nre, nrh;

inline int tata(int nod) { return nod/2; }
inline int fiu_stanga(int nod) { return nod*2; }
inline int fiu_dreapta(int nod) { return nod*2  +1; }

void schimba(int x, int y)
{
    int aux;
    aux = h[x];
    h[x] = h[y];
    h[y] = aux;

    p[ h[x] ] = x;
    p[ h[y] ] = y;

}

void urca(int nod)
{

    if(nod > 1 && v[ h[nod] ] < v[ h[tata(nod)] ])
    {
        schimba(nod, tata(nod));
        urca(tata(nod));
    }
}

void coboara(int nod)
{
    int ales;
    ales = nod;
    if(fiu_stanga(nod) <= nrh && v[ h[fiu_stanga(nod)] ] < v[ h[ales] ] ) ales = fiu_stanga(nod);
    if(fiu_dreapta(nod) <= nrh && v[ h[fiu_dreapta(nod)] ] < v[ h[ales] ] ) ales = fiu_dreapta(nod);
    if(ales != nod)
    {
        schimba(nod, ales);
        coboara(ales);
    }


}

int main ()
{
    f >> N;
    for(int i = 1; i <= N; i ++)
    {
        f >> tip;

        if(tip == 1)
        {
            f >> x;
            v[++ nre] = x;
            h[++ nrh] = nre;
            p[ h[nrh] ] = nrh;
            urca(nrh);
        }

        if(tip == 2)
        {
            f >> x;
            x = p[x];
            schimba(x, nrh--);
            urca(x);
            coboara(x);
        }

        if(tip == 3) g << v[ h[1] ] << '\n';
    }
    return 0;
}