Cod sursa(job #545549)

Utilizator BitOneSAlexandru BitOne Data 3 martie 2011 15:51:28
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <string>
#include <fstream>
#include <cstdlib>
#define N_MAX 29

using namespace std;
class Trie 
{
	bool root;
	int _countSetLetters;
	int _countApp;
	Trie* next[N_MAX];
public :
	Trie() : _countSetLetters(0), root(true), _countApp(0)
	{
		for( int i=0; i < N_MAX; ++i )
			next[i]=NULL;
	}
	void Add( string::const_iterator& it, string::const_iterator& iend )
	{
		if( it >= iend )
		{
			++_countApp;
			return;
		}
		int l=*it-'a';
		if( NULL == next[l] )
		{
			next[l]=new Trie();
			next[l]->root=false;
			++_countSetLetters;
		}
		next[l]->Add( it+1, iend );
	}
	bool Delete( string::const_iterator it, string::const_iterator& iend ) 
	{
		if( it >= iend )
			return true;
		int l=*it-'a';
		if( next[l]->Delete(it+1, iend) )
		{
			next[l]=NULL;
			--_countSetLetters;
		}
		if( !root && 0 == _countSetLetters )
		{
			delete this;
			return true;
		}
		return false;
	}
	int CountApp( string::const_iterator it, string::const_iterator& iend )
	{
		if( it >= iend )
			return _countApp;
		int l=*it-'a';
		int x;
		if( NULL == next[l] || 0 == (x=next[l]->CountApp(it+1, iend)) )
			return 0;
		return x;
	}
	int LCP( string::const_iterator it, string::const_iterator& iend )
	{
		if( it >= iend )
			return 0;
		int l=*it-'a';
		if( NULL == next[l] )
			return 0;
		return 1+next[l]->LCP( it+1, iend );
	}
};
int main( void )
{
	Trie* r=new Trie;
	int op;
	string word;
	ifstream in( "trie.in" );
	ofstream out( "trie.out" );
	while( in>>op>>word )
	{
		switch(op)
		{
			case 0 : r->Add(word.begin(), word.end()); break;
			case 1 : r->Delete(word.begin(), word.end()); break;
			case 2 : out<<r->CountApp(word.begin(), word.end())<<'\n'; break;
			case 3 : out<<r->LCP(word.begin(), word.end())<<'\n'; break;
		}
	}
	return EXIT_SUCCESS;
}