Cod sursa(job #1429530)

Utilizator TPotecTiberiu Potec TPotec Data 6 mai 2015 16:30:24
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
using namespace std;

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

int n, nh, h[10000001], poz[10000001], v[10000001];

void schimb(int p, int q)
{
    int aux = h[p];
    h[p] = h[q];
    h[q] = aux;
    poz[h[p]]=p;
    poz[h[q]]=q;
}

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

void coboara(int p)
{
    int fs=2*p;
    int fd=2*p+1;
    int 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)
    {
        schimb(p,bun);
        coboara(bun);
    }
}

void adaugaH(int x)
{
    h[++nh]=x;
    urca(nh);
}

void stergeH(int p)
{
    schimb(p,nh--);
    urca(p);
    coboara(p);
}

int main()
{
    int i, x,operatie;
    in >> n;
    for (i = 1; i <= n; i++)
    {
        in >> operatie;
        if(operatie==1)
        {
            in>>x;
            adaugaH(x);
        }
        if(operatie==2)
        {
            in>>x;
            stergeH(x);
        }
        {
            if(operatie==3)
            {
                out<<h[1]<<'\n';
            }
        }
    }
    return 0;
}