Cod sursa(job #1773328)

Utilizator ovidiu_zic@yahoo.comPurecel Mihai [email protected] Data 7 octombrie 2016 18:54:00
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int Nmax = 200001;

int h[Nmax], nh, v[Nmax], nr, poz[Nmax];

void schimba( int p, int q )
{

    int aux = h[p];
    h[p] = h[q];
    h[q] = aux;
    poz[ h[p] ] = p;
    poz[ h[q] ] = q;
}

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

    if( fd<=nh && v[ h[fd] ] < v[ h[bun] ] )
        bun = fd;

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

void urca( int p )
{
    while( p!=1 && v[h[p]] < v[h[p/2]] )
    {
        schimba(p, p/2);
        p /= 2;
    }
}

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

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

int main()
{
    int x, N, n, operatie;
    in>>N;

    for(int i = 1; i<=N; i++)
    {
        in>>operatie;

        if(operatie == 1)
        {
            in>>x;
            v[++nr] = x;
            adauga(nr);
        }

        if(operatie == 2)
        {
            in>>x;
            sterge(poz[x]);
        }

        if(operatie == 3)
            out<<v[h[1]]<<"\n";
    }

    return 0;
}