Cod sursa(job #2416379)

Utilizator GoogalAbabei Daniel Googal Data 27 aprilie 2019 14:41:29
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 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];
int 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 move_sift_12(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
        move_sift_12(n, k);
}

int main()
{
    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;
            delete_elem(nr, z[x]);
        }
        else
            out<<v[minheap()]<<'\n';
    }

    in.close();
    out.close();

    return 0;
}