Cod sursa(job #2416502)

Utilizator AlexNeaguAlexandru AlexNeagu Data 27 aprilie 2019 17:06:37
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
const int NMAX=200005;
int T[NMAX],N,X,Y,L=0,K=0;
struct Tabel
{
    int Value;
    int Position;
} Heap[NMAX],aux;
int Father (int X)
{
    return X/2;
}
int Left_Son(int X)
{
    return X*2;
}
int Right_Son(int X)
{
    return X*2+1;
}

void Upheap(int x)
{
   while(Heap[Father(x)].Value > Heap[x].Value && Father(x))
	{
		T[Heap[Father(x)].Position] = x;
		T[Heap[x].Position] = Father(x);

		aux = Heap[Father(x)];
		Heap[Father(x)] = Heap[x];
		Heap[x] = aux;
		x = Father(x);
	}
}
void Downheap(int x)
{
    int Son;
	do
	{
		Son = 0;
		if(Left_Son(x) <= L)
		{
			Son = Left_Son(x);
			if (Right_Son(x) <= L && Heap[Son].Value >= Heap[Right_Son(x)].Value)
				Son = Right_Son(x);
		}
		if(Heap[Son].Value >= Heap[x].Value)
			Son = 0;

		if(Son)
		{
			T[Heap[Son].Position] = x;
			T[Heap[x].Position] = Son;
			aux = Heap[Son];
			Heap[Son] = Heap[x];
			Heap[x] = aux;
			x = Son;
		}
	}while(Son);
}
void Insert(int x)
{
    Heap[++L].Value = x;
	Heap[L].Position = K+1;
	T[++K] = L;
	Upheap(L);
}
void Pop(int x)
{
    x = T[x];
	Heap[x] = Heap[L--];
	Downheap(x);
	if(Heap[Father(x)].Value > Heap[x].Value && Father(x))
		Upheap(x);
}
int main()
{
    fin>>N;
    while (N--)
    {
        fin>>X;
        if (X==1)
        {
            fin>>Y;
            Insert(Y);
        }
            if (X==2)
        {
            fin>>Y;
            Pop(Y);
        }
            if (X==3)
            fout<<Heap[1].Value<<"\n";
    }
    return 0;
}