Cod sursa(job #727888)

Utilizator OwnedCheciches Marius Owned Data 28 martie 2012 12:41:01
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>
#include <algorithm>
using namespace std;

long a[200001],heap[200001],pos[200001],n,m;

void push(int k){
	int x,key;
	x=k;
	key=a[heap[k]];
	while(x/2&&key<a[heap[x/2]]){
		pos[x/2]=x;
		heap[x]=heap[x/2];
		x=x/2;}
	pos[k]=x;
	heap[x]=k;}

void pop(int k){
	pos[k]=0;
	int son;
	heap[k]=heap[m];
	m--;
	if(k>1&&a[heap[k]]<a[heap[k/2]])
		push(k);
	else 
		do{
			son=0;
			if(k*2<=m)
				son=heap[k*2];
			if(k*2+1<=m&&a[heap[k*2]]>a[heap[k*2+1]])
				son=heap[k*2+1];
			if(a[heap[son]]>a[heap[k]])
				son=0;
			if(son){
				swap(pos[son],pos[k]);
				swap(heap[son],heap[k]);
				k=son;}}
		while(son);}

int main(){
	int nr;
	ifstream f("heapuri.in");
	ofstream g("heapuri.out");
	f>>nr;
	int o,x;
	for(int i=1;i<=nr;i++){
		f>>o;
		if(o<3)
			f>>x;
		if(o==1){
			n++;
			m++;
			a[n]=x;
			pos[n]=m;
			heap[m]=n;
			push(m);}
		if(o==2)
			pop(pos[x]);
		if(o==3)
			g<<a[heap[1]]<<"\n";}
	f.close();
	g.close();
	return 0;}