Cod sursa(job #2797028)

Utilizator NeuerRaducu Ioan Stefan Neuer Data 9 noiembrie 2021 10:20:02
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <fstream>

using namespace std;
const int SIZE = 2e5+10;

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

int n, qry, x;
int heap[SIZE], hn, pos[SIZE], indpos[SIZE], pn;

void afis()
{
    int p2=1;
    for(int i=1; i<=hn; i++)
    {
        cout<<pos[i]<<' ';
        if(p2+p2/2==i) p2*=2, cout<<"\n";
    }
}

void upheap(int ind)
{
    while(ind>1 && heap[ind/2]>heap[ind])
        swap(heap[ind], heap[ind/2]),
        swap(indpos[ind], indpos[ind/2]),
        pos[indpos[ind]] = ind,
        pos[indpos[ind/2]] = ind/2;
}

void downheap(int ind)
{
    if(ind*2>hn) return;
    int great = ind, st, dr;
    st = ind*2, dr = st + 1;
    if(heap[st]<heap[ind]) great = st;
    if(dr<=hn && heap[dr]<heap[great]) great = dr;
    if(great == ind) return;
    swap(heap[ind], heap[great]),
    swap(indpos[ind], indpos[great]);
    pos[indpos[ind]] = ind;
    pos[indpos[great]] = great;
}

void hinsert(int nr)
{
    heap[++hn] = nr;
    swap(heap[hn], heap[1]);
    pos[++pn] = 1;
    swap(indpos[hn], indpos[1]);
    indpos[1] = pn;
    upheap(hn);
}

void hremove(int indp)
{
    int ind = pos[indp];
    swap(heap[ind], heap[hn]),
    swap(indpos[ind], indpos[hn]);
    pos[indpos[ind]] = ind,
    pos[indpos[hn]] = hn;
    hn--;
    downheap(ind);
}

int main()
{
    cin>>n;
    for(int i=1; i<=n; i++)
    {
        cin>>qry;
        if(qry<3) cin>>x;
        if(qry == 1) hinsert(x);
        else if(qry == 2) hremove(x);
        else cout<<heap[1]<<'\n';
        //cout<<"\n$$\n";
        //afis();
        //cout<<"\nEnd $$\n";
    }
    return 0;
}