Cod sursa(job #458982)

Utilizator darrenRares Buhai darren Data 27 mai 2010 14:31:28
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include<fstream>
using namespace std;

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

int op;
int h[200001], n;
int nod[200001], ex[200001], now;

void push(int x);
void pop(int x);

int main()
{
	fin >> op;
	int p1, p2;
	for (int i = 0; i < op; ++i)
	{
		fin >> p1;
		if (p1 == 1)
		{
			++now;
			fin >> p2;
			push(p2);
		}
		if (p1 == 2)
		{
			fin >> p2;
			pop(p2);
		}
		if (p1 == 3)
			fout << h[1] << '\n';
	}
	return 0;
}

void push(int x)
{
	++n;
	h[n] = x;
	int f = n, t = n / 2;
	
	nod[f] = now; // cel de pe poz f, este ale now-lea
	ex[now] = f; // al now-lea este cel de pe poz f
	while (t > 0 && h[f] < h[t])
	{
		swap(h[f], h[t]);
		
		ex[nod[f]] = t;
		ex[nod[t]] = f;
		swap(nod[f], nod[t]);
		
		f = t;
		t = f / 2;
	}
}

void pop(int x)
{
	h[ex[x]] = h[n];
	nod[ex[x]] = nod[n];
	ex[nod[n]] = ex[x];
	
	--n;
	int t = 1, f = 2;
	while (f <= n)
	{
		if (f + 1 <= n)
			f = h[f] > h[f + 1] ? f + 1 : f;
		if (h[t] > h[f])
		{
			swap(h[f], h[t]);
			
			ex[nod[f]] = t;
			ex[nod[t]] = f;
			swap(nod[f], nod[t]);
			
			t = f;
			f *= 2;
		}
		else
			break;
	}
}