Cod sursa(job #1371385)

Utilizator valentinpielePiele Valentin valentinpiele Data 3 martie 2015 21:08:40
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
using namespace std;

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

const int Nmax=200001;
int N;
int tip;
int v[Nmax], h[Nmax], p[Nmax];
int x;
int nre, nrh;

inline int tata(int nod) { return nod/2; }
inline int fiu_stanga(int nod) { return nod*2; }
inline int fiu_dreapta(int nod) { return nod*2+1; }

void schimba(int x, int y)
{
	int aux;
	aux=h[x];
	h[x]=h[y];
	h[y]=aux;
	
	p[h[x]]=x;
	p[h[y]]=y;
}


void urca(int nod)
{
	if(nod > 1 && v[nod] < v[tata(nod)])
	{
		schimba(nod, nod/2);
		urca(nod/2);
	}
}

void coboara(int nod)
{
	int ales;
	ales = nod;
	
	if(fiu_stanga(nod) <= nrh && v[h[fiu_stanga(nod)]] < v[h[ales]]) ales=fiu_stanga(nod);
	if(fiu_dreapta(nod) <= nrh && v[h[fiu_dreapta(nod)]] < v[h[ales]]) ales=fiu_dreapta(nod);
	if(ales != nod)
	{
		schimba(nod, ales);
		coboara(ales);
	}
}

int main ()
{
	f >> N;
	for(int i=1; i<=N; i++)
	{
		f >> tip;
		if(tip == 1)
		{
			f >> x;
			v[++nre]=x;
			h[++nrh]=nre;
			p[h[nrh]]=nrh;
			urca(nrh);
		}
		if(tip == 2)
		{
			f >> x;
			x=p[x];
			schimba(x, nrh);
			nrh--;
			urca(x);
			coboara(x);
		}
		if(tip == 3)
			g << v[h[1]] << '\n';
	}
	return 0;
}