Cod sursa(job #1768316)

Utilizator AndreiDumitrescuAndrei Dumitrescu AndreiDumitrescu Data 30 septembrie 2016 18:04:24
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int  h[200001], val[200001], poz[200001];
int nh;

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 && val[h[fs]] < val[h[bun]]) bun = fs;
    if(fd <= nh && val[h[fd]] < val[h[bun]]) bun = fd;
    if(bun != p)
    {
        schimba(bun,p);
        coboara(bun);
    }
}

void urca(int p)
{
    while(p != 1 && val[h[p]] < val[h[p/2]] )
    {
        schimba(p, p/2);
        p /= 2;
    }
}
void adauga(int val1)
{
    h[++nh] = val1;
    poz[val1] = nh;
    urca(nh);
}

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

int main()
{
    int i, n,b, m = 0;
    f >> n;
    for(i = 1; i <= n ; i++)
    {
        int a;
        //nh++;
        f >> a;
        if(a == 1)
        {
            f >> b;
            m++;
            val[m] = b;
            adauga(m);
        }
        if(a == 2)
        {
            f >> b;
            sterge(poz[b]);
        }
        if(a == 3)
            g << val[h[1]] << '\n';
    }
}