Pagini recente » Cod sursa (job #1418160) | Cod sursa (job #1006393) | Cod sursa (job #2542697) | Cod sursa (job #1316266) | Cod sursa (job #460212)
Cod sursa(job #460212)
#include <cstdlib>
#include <fstream>
/*
*
*/
using namespace std;
typedef char str[31];
class trie
{
int CountAp, LPrefix, CountSons;
trie* next[ 31 ];
bool IsNC( char x )
{
return x < 'a' || x > 'z';
}
public :
trie( void ) : CountAp(0), LPrefix(0), CountSons(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->CountSons;
this->next[c]->LPrefix=this->LPrefix+1;
this->next[c]->Add( s+1 );
}
inline bool trie::Del( str s )
{
if( IsNC(s[0]) )
{
--this->CountAp;
if( 0 == this->CountAp && 0 == this->CountSons )
{
delete this;
return true;
}
return false;
}
int c=s[0]-'a';
if( this->next[c]->Del( s+1 ) )
this->next[c]=NULL, --this->CountSons;
if( root != this && 0 == this->CountAp && 0 == this->CountSons )
{
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;
}