Cod sursa(job #595104)

Utilizator balakraz94abcd efgh balakraz94 Data 11 iunie 2011 10:44:22
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include<cstdio>
#include<algorithm>
#define infile "heapuri.in"
#define outfile "heapuri.out"
#define n_max 200010 
#define father(x) x>>1
#define left_son(x) x<<1
#define right_son(x) (x<<1) + 1
using namespace std;

int N,nr;
int h[n_max],in[n_max],leg[n_max];


void sift(int k)
{
	int son=k,l,r;
	
	l=left_son(k);
	r=right_son(k);
	
	if(l<=N && h[l] < h[k])
		son=l;
	
	if(r<=N && h[r] < h[son])
		son=r;
	
	if(son!=k)
	{
		int i1,i2;
		
		i1=leg[k];
		i2=leg[son];
		
		swap(in[i1],in[i2]);
		
		swap(leg[k],leg[son]);
		
		swap(h[k],h[son]);
		
		sift(son);
	}
}


void percolate(int k)//k = pozitia in heap
{
	int key=h[k];//aici am nodul
	
	while(k>1 && key < h[father(k)] )
	{
	    int i1,i2;
		
		i1 = leg[k];
		i2=leg[father(k)];
		
		swap(in[i2],in[i1]);
		
		swap(leg[father(k)],leg[k]);
		
		swap(h[k],h[father(k)]);
		
		k = father(k);
	}
	
	h[k] = key;
	
	in[leg[k]]=k;
}



void insert(int x)//il inserez pe x
{
	in[++nr]=++N;//elementul cu nr de ordine nr se va gasi pe pozitia N in heap
	
	h[N]=x;//l-am pus pe x in heap
	
	leg[N]=nr;//leg pozitia din heap de cea de ordine
	
	percolate(N);
}


void cut(int k)
{
	h[k] = h[N];
	
	int i1 = leg[k], i2 = leg[N];
	
	in[i1] = in[i2];
	
	leg[k] = leg[N];
	
	if(k>1 && h[k] < h[father(k)])
		percolate(k);
	else
		sift(k);
}




int main()
{
	freopen(infile,"r",stdin);
    freopen(outfile,"w",stdout);
	
	int t,q,x;
	
	for(scanf("%d",&t);t;t--)
	{
		scanf("%d",&q);
		if(q<3)
		{
			scanf("%d",&x);
			if(q==1)
				insert(x);
			else 
				cut(in[x]);
		}
		else
			printf("%d\n",h[1]);
	}
	
	return 0;
}