Cod sursa(job #1369234)

Utilizator andreismara97Smarandoiu Andrei andreismara97 Data 2 martie 2015 22:49:54
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include<fstream>
#include<vector>
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");

#define Nmax 200001

int h[Nmax], poz[Nmax], d[Nmax];
int nh=0, nr=0;
int n;

void schimba(int i1, int i2)
{
    int aux = h[i1];
    h[i1] = h[i2];
    h[i2] = aux;

    poz[h[i1]] = i1;
    poz[h[i2]] = i2;
}

void urca(int i)
{
    while( i>1 && d[h[i]] < d[h[i / 2]])
    {
        schimba(i, i/2);
        i/=2;
    }
}

void coboara(int i)
{
    int bun = i, fs = i*2, fd = i*2+1;
    if( fs<=nh && d[h[fs]] < d[h[bun]])
        bun = fs;
    if( fd<=nh && d[h[fd]] < d[h[bun]])
        bun = fd;

    if(i != bun)
    {
        schimba(i, bun);
        coboara(bun);
    }
}

void adauga(int x)
{
    d[++nr] = x;
    h[++nh] = nr;
    poz[x] = nh;
    urca(nh);
}

void sterge(int i)
{
    schimba(i, nh);
    nh--;
    coboara(i);
    urca(i);
}

void solve()
{
    int x, cod;
    in >> n;
    for(int i=1; i<=n; i++)
    {
        in >> cod;
        if(cod < 3)
        {
            in >> x;
            if(cod == 1)
                adauga(x);
            else
                sterge(poz[x]);
        }
        else
            out <<d[h[1]]<<'\n';
    }
}

int main ()
{
    solve();
    return 0;
}