Cod sursa(job #615635)

Utilizator BitOneSAlexandru BitOne Data 10 octombrie 2011 14:04:24
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.38 kb
#include <string>
#include <fstream>
#include <cstdlib>
#define N_MAX 

using namespace std;
class Trie
{
	Trie *v[31];
	int countSons, countApp;
	bool Delet( string::const_iterator it, const string::const_iterator& iend );
public :
	Trie() : countSons(0), countApp(0)
	{
		for( int i=0; i < 31; ++i )
			v[i]=NULL;
	}
	void Add( string::const_iterator it, const string::const_iterator& iend );
	void Delete( string::const_iterator it, const string::const_iterator& iend );
	int GetApp( string::const_iterator it, const string::const_iterator& iend );
	int GetLongestPrefix( string::const_iterator it, const string::const_iterator& iend );
} *root=new Trie();
void Trie::Add( string::const_iterator it, const string::const_iterator& iend )
{
	if( it >= iend )
		++countApp;
	else {
			int cIndex=*it-'a';
			if( NULL == v[cIndex] )
				v[cIndex]=new Trie(), ++countSons;
			v[cIndex]->Add( it+1, iend );
		 }
}
bool Trie::Delet( string::const_iterator it, const string::const_iterator& iend )
{
	if( it >= iend )
	{
		--countApp;
		if( countApp <= 0 )
		{
			countApp=0; 
			if( 0 == countSons )
				return true;
		}
		return false;
	}
	int cIndex=*it-'a';
	if( NULL == v[cIndex] ) //this should not happen, normaly nothing should happen
		exit(1);
	if( v[cIndex]->Delet( it+1, iend ) )
	 v[cIndex]=NULL, --countSons;
	if( this != root && 0 == countSons && 0 == countApp )
	{
		delete this;
		return true;
	}
	return false;
}
void Trie::Delete( string::const_iterator it, const string::const_iterator& iend )
{
	Delet( it, iend );
}
int Trie::GetApp( string::const_iterator it, const string::const_iterator& iend )
{
	if( it >= iend )
		return countApp;
	else {
			int cIndex=*it-'a';
			if( NULL == v[cIndex] )
				return 0;
			return v[cIndex]->GetApp( it+1, iend );
		 }
}
int Trie::GetLongestPrefix( string::const_iterator it, const string::const_iterator& iend )
{
	if( it >= iend )
		return 0;
	else {
			int cIndex=*it-'a';
			if( NULL == v[cIndex] )
				return 0;
			return 1+v[cIndex]->GetLongestPrefix( it+1, iend );
		 }
}
int main( void )
{
	int op;
	string s;
	ifstream in( "trie.in" );
	ofstream out( "trie.out" );
	while( in>>op>>s )
	{
		switch(op)
		{
			case 0 : root->Add( s.begin(), s.end() ); break;
			case 1 : root->Delete( s.begin(), s.end() ); break;
			case 2 : out<<root->GetApp( s.begin(), s.end() )<<'\n'; break;
			case 3 : out<<root->GetLongestPrefix( s.begin(), s.end() )<<'\n';
		}
	}
	return EXIT_SUCCESS;
}