Cod sursa(job #460209)

Utilizator BitOneSAlexandru BitOne Data 1 iunie 2010 17:00:58
Problema Trie Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.16 kb
#include <cstdlib>
#include <fstream>

/*
 *
 */
using namespace std;
typedef char str[31];
class trie
{
    int CountAp, LPrefix;
    trie* next[ 31 ];
    bool IsNC( char x )
    {
        return x < 'a' || x > 'z';
    }
public :
    trie( void ) : CountAp(0), LPrefix(0)
    {
        for( int i=0; i < 31; ++i )
            next[i]=NULL;
    }
    inline void Add( str );
    inline bool Del( str );
    inline int App( str );
    inline int Lcp( str );
} *root;
inline void trie::Add( str s )
{
    if( IsNC( s[0] ) )
    {
        ++this->CountAp;
        return;
    }
    int c=s[0]-'a';
    if( NULL == this->next[c] )
        this->next[c]=new trie;
    this->next[c]->LPrefix=this->LPrefix+1;
    this->next[c]->Add( s+1 );
}
inline bool trie::Del( str s )
{
	int i;
    if( IsNC(s[0]) )
    {
        --this->CountAp;
		for( i=0; i < 31; ++i )
			if( this->next[i] )
				break;
        if( 0 == this->CountAp && 31 == i )
        {
            delete this;
            return true;
        }
        return false;
    }
    int c=s[0]-'a';
    if( this->next[c]->Del( s+1 ) )
        this->next[c]=NULL;
	for( i=0; i < 31; ++i )
		if( this->next[i] )
			break;
    if( 0 == this->CountAp && 31 == i )
    {
        delete this;
        return true;
    }
    return false;
}
inline int trie::App( str s )
{
    if( IsNC(s[0]) )
        return this->CountAp;
    int c=s[0]-'a';
    if( NULL == this->next[c] )
        return 0;
    return this->next[c]->App( s+1 );
}
inline int trie::Lcp( str s )
{
    if( IsNC(s[0]) )
        return this->LPrefix;
    int c=s[0]-'a';
    if( NULL == this->next[c] )
        return this->LPrefix;
    return this->next[c]->Lcp( s+1 );
}
str s;
int main( void )
{
    int i;
    ifstream in( "trie.in" );
    ofstream out( "trie.out" );
    root=new trie;
    while( in>>i>>s )
    {
        switch( i )
        {
            case 0 : root->Add( s ); break;
            case 1 : root->Del( s ); break;
            case 2 : out<<( root->App( s ) )<<'\n'; break;
            default : out<<( root->Lcp( s ) )<<'\n';
        }
    }
    return EXIT_SUCCESS;
}