Cod sursa(job #422425)

Utilizator alexandru92alexandru alexandru92 Data 22 martie 2010 17:56:00
Problema Sortare prin comparare Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.58 kb
//      hash_sort.cpp
//      
//      Copyright 2010 SpeeDemon <virtualdemon@ubuntu>
//      
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; either version 2 of the License, or
//      (at your option) any later version.
//      
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//      
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.
#include <cstdlib>
#include <fstream>
#define Modulo 666013

/*
 * 
 */
using namespace std;
struct pr
{
	int number, c;
	pr* next;
} *F[Modulo], *L[Modulo];
typedef pr* list;
inline void insert( const int& x, const int& p )
{
	if( !F[p] ) //the list it vid
	{
		list q=new pr;
		q->number=x;
		q->c=1;
		q->next=NULL;
		F[p]=L[p]=q;
		return;
	}
	if( F[p]->number == x )
	{
		++F[p]->c;
		return;
	}
	if( L[p]->number == x )
	{
		++L[p]->c;
		return;
	}
	if( F[p] == L[p] ) //we have a single element in the list
	{
		list q=new pr;
		q->number=x;
		q->c=1;
		q->next=NULL;
		if( F[p]->number > x )
		{
			F[p]=q;
			F[p]->next=L[p];
			return;
		}
		L[p]=q;
		F[p]->next=L[p];
		return;
	}
	if( F[p]->number > x )
	{
		list q=new pr;
		q->number=x;
		q->c=1;
		q->next=F[p];
		F[p]=q;
		return;
	}
	if( L[p]->number < x )
	{
		list q=new pr;
		q->number=x;
		q->c=1;
		q->next=NULL;
		L[p]->next=q;
		L[p]=q;
		return;
	}
	list z;
	for( z=F[p]; z->next && z->next->number < x; z=z->next );
	if( z->next && z->next->number == x )
	{
		++z->next->c;
		return;
	}
	list q=new pr;
	q->number=x;
	q->c=1;
	q->next=z->next;
	z->next=q;
}
inline int pop( const int& p, int& h )
{
	int number=F[p]->number;
	h=F[p]->c;
	list q=F[p];
	F[p]=F[p]->next;
	if( !F[p] )
		F[p]=L[p]=NULL;
	delete q;
	return number;
}
int main( void )
{
	int N, i, x, maxim=-1, to;
	ifstream in( "algsort.in" );
	ofstream out( "algsort.out" );
	in>>N;
	for( i=0; i < N; ++i )
	{
		in>>x;
		maxim=max( x%Modulo, maxim );
		insert( x, x%Modulo );
	}
	do
	{
		for( i=0, to=maxim, maxim=-1; i <= to; ++i )
			if( F[i] )
			{
				x=pop( i, N );
				for( ; N; --N )
					out<<x<<' ';				
				if( F[i] )
					maxim=i;
			}
	}while( maxim != -1 );
	return EXIT_SUCCESS;
}