Cod sursa(job #3131392)

Utilizator alexdumitruAlexandru Dumitru alexdumitru Data 19 mai 2023 23:07:36
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <fstream>

using namespace std;

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

const int NMAX = 2e5+5;

int n, t, cnt;
int heap[NMAX];
int tiempo[NMAX];
int donde[NMAX];

void my_swap(int x, int y)
{
    swap(heap[x], heap[y]);
    swap(donde[tiempo[x]], donde[tiempo[y]]);
    swap(tiempo[x], tiempo[y]);
}

void arriba(int nod)
{
    if(nod == 1)
        return;
    int dad = nod >> 1;
    if(heap[dad] > heap[nod])
    {
        my_swap(dad, nod);
        arriba(dad);
    }
}

void abajo(int nod)
{
    int ls = nod << 1;
    int rs = ls + 1;
    if(ls > n)
        return;
    if(ls == n)
    {
        if(heap[nod] > heap[ls])
            my_swap(nod, ls);
        return;
    }
    int pos = ls;
    if(heap[ls] > heap[rs])
        pos = rs;
    if(heap[nod] > heap[pos])
    {
        my_swap(nod, pos);
        abajo(pos);
    }
}

void Insert(int x)
{
    heap[++n] = x;
    arriba(donde[tiempo[n] = ++cnt] = n);
}

void Delete(int x)
{
    int pos = donde[x];
    my_swap(pos, n--);
    if(pos > 1 && heap[pos] < heap[pos >> 1])
        arriba(pos);
    else abajo(pos);
}

void solve()
{
    fin >> t;
    while(t--)
    {
        int tip, x;
        fin >> tip;
        if(tip == 3)
            fout << heap[1] << '\n';
        else {
            fin >> x;
            if(tip == 1)
                Insert(x);
            else Delete(x);
        }
    }
}

int main()
{
    solve();
    return 0;
}