Cod sursa(job #728992)

Utilizator OwnedCheciches Marius Owned Data 29 martie 2012 10:12:44
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

#define maxn 200001
int a[maxn],heap[maxn],pos[maxn],n,np,nh;

void sw(int a,int b){
	swap(heap[a],heap[b]);
	pos[heap[a]]=a;
	pos[heap[b]]=b;}

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

void pull(int k){
	int son;
	do{
		son=0;
		if(k*2<=nh)
			son=k*2;
		if(k*2+1<=nh&&a[heap[son]]>a[heap[k*2+1]])
			son=k*2+1;
		if(a[heap[son]]>a[heap[k]])
			son=0;
		if(son){
			sw(k,son);
			k=son;}}
	while(son);}

void pop(int k){
	sw(k,nh);
	pos[heap[nh]]=0;
	nh--;
	if(a[heap[k]]<a[heap[k/2]]&&k/2)
		push(k);
	else
		pull(k);}

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