Cod sursa(job #1866373)

Utilizator xtreme77Patrick Sava xtreme77 Data 2 februarie 2017 22:35:55
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <vector>

using namespace std ;

ifstream fin ("algsort.in") ;
ofstream fout ("algsort.out") ;

class Heap {

public :
	vector < int > Hheap ; 
	int sz ;
	Heap ( int N )
	{
		Hheap.resize ( N ) ;
		sz = 0 ;
	}
	void Push ( int NewNode ) {
		++ sz ;
		Hheap [sz] = NewNode ;
		Up (sz) ;
	}
	int Top ()
	{
		return Hheap [1] ;
	}
	void Pop ()
	{
		swap (Hheap[1] , Hheap[sz--]) ;
		Down(1) ;
	}
	bool Empty()
	{
		if ( sz != 0 )
			return false ;
		return true ;
	}
private :
	void Up ( int nod )
	{
		while ( ( nod >> 1 ) > 0 and Hheap [nod] < Hheap [nod>>1] ) {
			swap (Hheap [nod] , Hheap [nod >> 1]) ;
			nod >>= 1 ;
		}
	}
	void Down ( int nod ) {
		while ( (nod << 1) <= sz ) {
			if ( Hheap [nod] > Hheap [nod<<1] and ( (nod << 1 |1) > sz or
			Hheap [nod<<1|1] > Hheap [nod<<1] ) ) {
				swap (Hheap [nod], Hheap [nod<<1]) ;
				nod <<= 1 ;
			}
			else if ( ((nod <<1)|1) <= sz and Hheap [nod]  > Hheap [nod << 1|1] ) {
				swap (Hheap [nod], Hheap [nod <<1|1]) ;
				nod <<= 1 ;
				nod |= 1 ;
			}
			else {
				break ;
			}
		}
	}

};

Heap *H = new Heap (500014) ;

int main()
{
	int n ;
	fin >> n ; 
	for ( int i = 1 ; i <= n ; ++ i ) {
		int x ; 
		fin >> x ;
		H -> Push (x) ; 
	}
	while ( !H-> Empty() ) {
		fout << H -> Top() << ' ' ;
		H -> Pop() ; 
	}
	return 0 ;
}