Cod sursa(job #586519)

Utilizator Rhadoo91Pavel Radu Rhadoo91 Data 2 mai 2011 11:04:40
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.06 kb

#include<iostream>
using namespace std;
#include <stdio.h>


class heap
{

int *poz;
int nr_poz;

int*	H;
int		N;

public:
	
	heap()
		{	
			poz = new int [200000];
			nr_poz =0;

			H = new int [200000];
			N = 0;
		}



int		father ( int nod )
	{
		return nod/2;
	}

int		left_son( int nod )
	{
		return nod * 2;
	}

int		right_son( int nod )
	{
		return nod * 2 + 1;
	}


int		max ()
	{
		return H[1];
	}

int		min_son ( int k )
	{
		int		son = 0;

		if ( left_son(k)<=N )
		{
		 son = left_son(k);

			if ( right_son(k)<=N && H[ right_son(k) ] < H[ son ] )
				son = right_son(k);
			}

	return son;		
	}

void	sift (int k)
	{
		int		son = 0;

		do
			{
				son = min_son ( k );
				
				if( H[ k ] < H [ son ] )
					son = 0;

				if( son )
					{
						int temp;
						temp = H [ son ];
						H [ son ] = H [ k ];
						H[ k ] = temp;

						k = son;
					}
				
			
			}while(son);

	
	}

int		percolate ( int k )
	{
		int key = H[ k ];		

		while ( k>1 && H[father(k)]>H[k])
			{
				H[ k ] = H [ father(k) ];
				k = father(k);
				H[k] = key;
			}
		return k;
	}

int		push( int x)
	{
		H [ ++N ] = x;
		return percolate ( N );

	}

int		pop ( int k )
	{
		int temp = H[k];

		H [ k ] = H [N];	N--;

		if (k>1 && H[father(k)]>H[k])
			percolate ( k );
		else
			sift( k );
	
		return temp;
	}

void	afiseaza (FILE *g)
	{
		for( int i=1; i<= N; i++)
			fprintf(g,"%d ", H[i]);
	}


void	ruleaza(FILE * f, FILE *g)
	{
		int n;
		fscanf(f, "%d",&n);
		int x = 0;
		for(int i=1 ; i<=n; i++)
			{
				fscanf(f, "%d", &x );
				if(x ==1 )
					{
						int y;	fscanf(f,"%d",&y);
						
							poz[++nr_poz] = push(y);
					}
				else
					if(x==2)
						{
							int y;	fscanf(f,"%d",&y);

							fprintf(g,"%d\n",pop(poz[y]));
						}
					else
						fprintf(g,"%d\n",max());
			}
	}


}; //eof class heap


int main()
{
FILE *f, *g;
f = fopen( "heapuri.in","r" );
g = fopen( "heapuri.out","w" );

heap H;
H.ruleaza(f,g);


return 0;
}