Cod sursa(job #2416387)

Utilizator GoogalAbabei Daniel Googal Data 27 aprilie 2019 14:48:08
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.27 kb
#include <fstream>
#include <algorithm>
#define HeapMax 200001

using namespace std;

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

int n,heap[HeapMax],v[HeapMax],z[HeapMax],code,x,nr,realno;

inline int father(int k)
{
    return k/2;
}

inline int leftson(int k)
{
    return k*2;
}

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

inline int minheap()
{
    return heap[1];
}

void sift(int n, int k)
{
    int son;
    do
    {
        son=0;
        if(leftson(k)<=n)
        {
            son=leftson(k);
            if(rightson(k)<=n && v[heap[leftson(k)]]>v[heap[rightson(k)]])
                son=rightson(k);
            if(v[heap[son]]>=v[heap[k]])
                son=0;
        }

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

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

void insert_elem(int &n, int key)
{
    heap[++n]=key;
    z[key]=n;
    percolate(n,n);
}

void delete_elem(int &n, int k)
{
    heap[k]=heap[n];
    z[heap[k]]=k;
    n--;
    if(k>1 && heap[k]<heap[father(k)])
        percolate(n,k);
    else
        sift(n,k);
}

/*int search_elem(int key, int poz)
{
    if(heap[poz]==key)
        return poz;
    else
    {
        if(heap[leftson(poz)]<=key)
            return search_elem(key, leftson(poz));
        if(heap[rightson(poz)<=key])
            return search_elem(key, rightson(poz));
    }
    return 0;
{1}
    for(int i=1; i<=nr; i++)
        if(heap[i]==key)
            return i;
}*/

int main()
{
    //int r;
    in>>n;
    for(int i=1; i<=n; i++)
    {
        in>>code;
        if(code==1)
        {
            in>>x;
            v[++realno]=x;
            insert_elem(nr, realno);
        }
        else if(code==2)
        {
            in>>x;
            //r=search_elem(v[x], 1);
            delete_elem(nr, z[x]);
        }
        else
            out<<v[minheap()]<<'\n';
    }
    in.close();
    out.close();
    return 0;
}