Cod sursa(job #1583083)

Utilizator cordun_cristinaCristina Maria Cordun cordun_cristina Data 28 ianuarie 2016 18:27:46
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <fstream>
using namespace std;

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

const int NMax = 200005;

int N,M,NHeap;
int Heap[NMax];
int A[NMax],Poz[NMax];

void Swap(int Nod, int Tata)
{
    swap(Heap[Nod],Heap[Tata]);
    swap(Poz[Heap[Nod]],Poz[Heap[Tata]]);
}

void UpHeap(int Nod)
{
    int Tata = Nod / 2;

    if(Tata && A[Heap[Tata]] > A[Heap[Nod]])
        {
            Swap(Nod,Tata);
            UpHeap(Tata);
        }
}

void DownHeap(int Nod)
{
    int Son = 2*Nod;

    if(Son > NHeap)
        return;

    if(Son == NHeap && A[Heap[Son]] < A[Heap[Nod]])
        {
            Swap(Son,Nod);
            return;
        }

    if(A[Heap[Son]] < A[Heap[Son+1]])
        {
            if(A[Heap[Son]] < A[Heap[Nod]])
                {
                    Swap(Son, Nod);
                    DownHeap(Son);
                }
        }
    else
        {
            if(A[Heap[Son+1]] < A[Heap[Nod]])
                {
                    Swap(Son+1, Nod);
                    DownHeap(Son+1);
                }
        }
}

int main()
{
    fin>>N;
    while(N--)
    {
        int op;
        fin>>op;
        if(op == 1)
            {
                int x;
                fin>>x;
                A[++M] = x;
                Heap[++NHeap] = M;
                Poz[M] = NHeap;
                UpHeap(NHeap);
            }
        if(op == 2)
            {
                int x;
                fin>>x;
                Heap[Poz[x]] = Heap[NHeap--];
                DownHeap(Poz[x]);

            }
        if(op == 3)
            {
                fout<<A[Heap[1]]<<"\n";
            }
    }
    return 0;
}