Cod sursa(job #766313)

Utilizator roxyroxy2011Luca Roxana roxyroxy2011 Data 10 iulie 2012 23:11:46
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <fstream>
#include <stdlib.h>
#define NRMAX 300001 

using namespace std;

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

int hp[NRMAX],ap[NRMAX],a[NRMAX],n,nr,l;

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

int main()
{
	f>>n;a[0]=1000000000;
	for (int i=1;i<=n;i++)
	{
		int tp,x,p;
		f>>tp;
		switch (tp)
		{
		case 1:
			f>>x;
			push(x);
			break;
		case 2:
			f>>p;
			pop(p);
			break;
		case 3:g<<a[hp[1]]<<'\n';
		}
	}
	f.close();g.close();
	return 0;
}

void push(int val)
{
	nr++;l++;
	a[nr]=val;
	ap[nr]=l;
	hp[l]=nr;
	
	int poz=l;
	while (a[hp[poz]]<a[hp[poz/2]] && poz/2>0)
	{
		int aux=hp[poz];
		hp[poz]=hp[poz/2];
		hp[poz/2]=aux;
		
		int x=hp[poz],y=hp[poz/2];
		aux=ap[x];ap[x]=ap[y];
		ap[y]=aux;
		poz=poz/2;
	}
}

void pop(int poz)
{
	int x=ap[poz],aa=hp[ap[poz]];
	hp[ap[poz]]=hp[l];
	hp[l]=aa;
	
	int y=0;
	while (x!=y)
	{
		y=x;
		if (y*2<=l && a[hp[2*y]]<a[hp[x]]) x=y*2;
		if (y*2+1<=l && a[hp[2*y+1]]<a[hp[x]])x=y*2+1;
		
		int aux=hp[x];
		hp[x]=hp[y];
		hp[y]=aux;
		
		ap[hp[x]]=x;
		ap[hp[y]]=y;
		
	}
}