Cod sursa(job #665053)

Utilizator SebiSebiPirtoaca George Sebastian SebiSebi Data 21 ianuarie 2012 16:12:25
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include<iostream>
#include<fstream>
using namespace std;
int v[400001],poz[200001],heap[200001],n,l;
void push(int x)
{
	int aux;
	while((x/2)&&(v[heap[x]]<v[heap[x/2]])) {
		aux=heap[x];
		heap[x]=heap[x/2];
		heap[x/2]=aux;
		poz[heap[x]]=x;
		poz[heap[x/2]]=x/2;
	}
}
void pop(int x)
{
	int aux,y;
	y=0;
	while(x!=y) {
		y=x;
		if(((2*y)<=l)&&(v[heap[2*y]]<v[heap[y]]))
			x=y*2;
		if(((2*y+1)<=l)&&(v[heap[2*y+1]]<v[heap[y*2+1]]))
			x=y*2+1;
		aux=heap[x];
		heap[x]=heap[y];
		heap[y]=aux;
		poz[heap[x]]=x;
		poz[heap[y]]=y;
	}
}
int main ()
{
	int i,op,m,x;
	ifstream f("heapuri.in");
	ofstream g("heapuri.out");
	f>>m;
	for(i=1;i<=m;i++) {
		f>>op;
		if(op==1) {
			f>>x;
			n++;
			l++;
			v[n]=x;
			heap[l]=n;
			poz[n]=l;
			push(l);
		}
		else if(op==2) {
			f>>x;
			x=poz[x];
			heap[x]=heap[l];
			l--;
			if((x>1)&&(v[heap[x]]<v[heap[x/2]]))
				push(x);
			else pop(x);
		}
		else g<<v[heap[1]]<<'\n';
	}
	f.close();
	g.close();
	return 0;
}