Cod sursa(job #2615266)

Utilizator As932Stanciu Andreea As932 Data 13 mai 2020 23:06:42
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <fstream>

using namespace std;

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

const int nmax=200005;

int n,cod,cnt,m;
int h[nmax],pos[nmax];
long long v[nmax],x;

int father(int nod)
{
    return nod/2;
}

int leftSon(int k)
{
    return 2*k;
}

int rightSon(int k)
{
    return 2*k+1;
}

void percolate(int heap[],int k)
{
    while(k>1 && v[heap[k]]<v[heap[father(k)]])
    {
        swap(heap[k],heap[father(k)]);
        pos[heap[k]]=k;
        pos[heap[father(k)]]=father(k);
        k=father(k);
    }
}

void sift(int heap[],int k)
{
    int son;

    do
    {
        son=0;

        if(leftSon(k)<=m)
        {
            son=leftSon(k);
            if(rightSon(k)<=m && v[heap[rightSon(k)]]<v[heap[leftSon(k)]])
                son=rightSon(k);

            if(v[heap[son]]>=v[heap[k]])
                son=0;
        }

        if(son)
        {
            swap(heap[son],heap[k]);
            pos[heap[son]]=son;
            pos[heap[k]]=k;
            k=son;
        }
    }
    while(son);
}

void cut(int heap[],int pozElim)
{
    int k=pos[pozElim];
    heap[k]=heap[m];
    pos[heap[k]]=pos[heap[m]];

    --m;

    if(k>1 && v[heap[k]]<v[heap[father(k)]])
        percolate(heap,k);
    else
        sift(heap,k);
}

int main()
{
    cin>>n;

    for(int i=1;i<=n;i++)
    {
        cin>>cod;

        if(cod==1)
        {
            cin>>x;

            ++cnt;
            ++m;

            v[cnt]=x;
            h[m]=cnt;
            pos[cnt]=m;

            percolate(h,m);
        }
        else if(cod==2)
        {
            cin>>x;

            v[x]=-1;
            cut(h,x);
        }
        else
            cout<<v[h[1]]<<"\n";
    }

    return 0;
}