Cod sursa(job #2388896)

Utilizator Seba951Sebastian Boerescu Seba951 Data 26 martie 2019 17:16:56
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <fstream>

using namespace std;

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

const int N=200005;
int h[N], poz[N], v[N];
int n, nh;

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

void sterge(int p)
{
    if(p==nh)
    {
        nh--;
        return;
    }
    h[p]=h[nh--];
    poz[h[p]]=p;
    urca(p);
    coboara(p);
}

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