Cod sursa(job #2008527)

Utilizator rangal3Tudor Anastasiei rangal3 Data 6 august 2017 19:04:40
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <fstream>
#define in "heapuri.in"
#define out "heapuri.out"
#define N 200002
using namespace std;

ifstream fin(in);
ofstream fout(out);

int n,op,key,x;
int heap[N],ord[N],nrord;

inline void percolate(int nod)
{
    int aux = heap[nod];
    int nrordaux = ord[N];

    while( nod > 1 && aux < heap[nod/2])
    {
        heap[nod] = heap[nod/2];
        ord[nod] = ord[nod/2];
        nod /= 2;
    }
    heap[nod] = aux;
    ord[nod] = nrordaux;
}

inline void sift(int nod)
{
    int son;

    do
    {
        son = 0;
        if(2*nod <= n)
        {
            son = 2*nod;
            if(2*nod + 1 <=n && heap[2*nod + 1] < heap[2*nod])
                son = 2*nod + 1;
            if(heap[son] >= heap[nod])
                son = 0;
        }

        if(son)
        {
            swap(heap[son],heap[nod]);
            swap(ord[son],ord[nod]);
            nod = son;
        }

    } while(son);
}

inline void add_nod(int val)
{
    ++n;
    ++nrord;
    heap[n] = val;
    ord[n] = nrord;
    percolate(n);
}

inline int cauta(int ct)
{
    for(int i=1; i<=n; ++i)
        if(ord[i] == ct) return i;
}

inline void del_nod(int ct)
{
    int i = cauta(ct);
    ord[i] = ord[n];
    heap[i] = heap[n];
    --n;

    if(i > 1 && heap[i] < heap[i/2])
        percolate(i);
    else sift(i);
}

void afis_nod()
{
    fout<<heap[1]<<"\n";
}

int main()
{
    fin>>op;

    while(op--)
    {
        fin>>key;
        if(key < 3) fin>>x;

        if(key == 1)
            add_nod(x);
        else if(key == 2)
            del_nod(x);
        else afis_nod();

    }

    fin.close();
    fout.close();
    return 0;
}