Cod sursa(job #728720)

Utilizator OwnedCheciches Marius Owned Data 28 martie 2012 22:03:35
Problema Heapuri Scor 40
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=k;
		if(k*2<=nh&&a[heap[k*2]]<a[heap[son]])
			son=k*2;
		if(k*2+1<=nh&&a[heap[son]]>a[heap[k*2+1]])
			son=k*2+1;
		if(son!=k){
			sw(k,son);
			k=son;}}
	while(son!=k);}

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)
			if(nh)
				pop(pos[x]);
		if(o==3)
			g<<a[heap[1]]<<"\n";}
	f.close();
	g.close();
	return 0;}