Cod sursa(job #2391391)

Utilizator alexdumitrescuDumitrescu George Alex alexdumitrescu Data 28 martie 2019 20:08:26
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <fstream>
#define Nmax 200005
using namespace std;
ifstream fin ("heapuri.in");
ofstream fout ("heapuri.out");
struct elemheap
{
    int v, in;
}h[Nmax];
int o[Nmax], i, k, nr, n, op, x;
int tata(int x)
{
    if(x>1)
        return x/2;
    return -1;
}

void urca(int poz)
{
    elemheap key=h[poz];
    int t=tata(poz);
    while(t!=-1&&key.v<h[t].v)
    {
        h[poz]=h[t];
        o[h[t].in]=poz;
        poz=t;
        t=tata(poz);
    }
    h[poz]=key;
    o[h[poz].in]=poz;
}

void coboara(int poz)
{
    int l=poz*2, r=poz*2+1, minim=poz;
    if(l<=k&&h[l].v<h[minim].v)
        minim=l;
    if(r<=k&&h[r].v<h[minim].v)
        minim=r;
    if(minim!=poz)
    {
        swap(h[poz], h[minim]);
        o[h[poz].in]=poz;
        o[h[minim].in]=minim;
        coboara(minim);
    }
}

void del(int poz)
{
    h[poz]=h[k];
    o[h[poz].in]=poz;
    k--;
    int t=tata(poz);
    if(t!=-1&&h[t].v>h[poz].v)
        urca(poz);
    else coboara(poz);
}
int main()
{
    fin >> n;
    for(i=1;i<=n;i++)
    {
        fin >> op;
        if(op==3)
            fout << h[1].v << '\n';
        else
        {
            fin >> x;
            if(op==1)
            {
                nr++;
                k++;
                h[k].v=x;
                h[k].in=nr;
                o[nr]=k;
                urca(k);
            }
            else
                del(o[x]);
        }
    }
    return 0;
}