Cod sursa(job #1768381)

Utilizator ovidiu_zic@yahoo.comPurecel Mihai [email protected] Data 30 septembrie 2016 20:06:04
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int h[21], nh, v[200001], nr;
int poz[200001];

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;
    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;
}