Cod sursa(job #2567464)

Utilizator AlexBosneag26Bosneag Alexandru AlexBosneag26 Data 3 martie 2020 17:26:25
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>

using namespace std;

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

const int N = 200001;

int h[N], v[N], poz[N], nh;

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

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

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

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)
    {
        schimb(bun, p);
        coboara(bun);
    }
}

void sterge(int p)
{
    p = poz[p];
    schimb(nh--, p);
    urca(p);
    coboara(p);
}

int main()
{
    int n, k = 0, x, y;
    in >> n;
    for(int i = 1; i <= n; i++)
    {
        in >> x;
        if(x == 1)
        {
            in >> y;
            v[++k] = y;
            adauga(k);
        }
        if(x == 2)
        {
            in >> y;
            sterge(y);
        }
        if(x == 3)
        {
            out << v[h[1]] << "\n";
        }
    }
    return 0;
}