Cod sursa(job #2553835)

Utilizator DanSDan Teodor Savastre DanS Data 22 februarie 2020 12:19:26
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int N = 200001;
int h[N], v[N], poz[N];
int n, nh, tip, x, inh;

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

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

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

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

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


int main()
{
    inh = 0;
    in>>n;
    for(int i=1; i<=n; i++)
    {
        in>>tip;
        if(tip == 3)
        {
            out<<v[h[1]]<<'\n';
        }
        else
        {
            in>>x;
            if(tip == 1)
            {
                v[++inh] = x;
                adauga(inh);
            }
            else if(tip == 2)
            {
                sterge(poz[x]);
            }
        }
    }
    return 0;
}