Pagini recente » Cod sursa (job #444106) | Cod sursa (job #1302456) | Cod sursa (job #368199) | Cod sursa (job #1265704) | Cod sursa (job #450668)
Cod sursa(job #450668)
/*
* File: main.cpp
* Author: virtualdemon
*
* Created on May 8, 2010, 1:07 PM
*/
#include <cstdlib>
#include <fstream>
/*
*
*/
using namespace std;
typedef char* str;
class trie
{
trie* t[30];
int CountAp, CountSons;
bool IsNC( char x )
{
return x < 'a' || x > 'z';
}
public:
trie( void ) : CountAp(0), CountSons(0)
{
for( int i=0; i < 30; ++i )
t[i]=NULL;
}
inline void Add( str );
inline bool Del( str );
inline int CountWords( str );
inline int MaxPrefix( str, int& );
} *root;
inline void trie::Add( str s )
{
if( IsNC(s[0]) )
{
++this->CountAp;
return;
}
int c=s[0]-'a';
if( NULL == this->t[c] )
this->t[c]=new trie, ++this->CountSons;
this->t[c]->Add( s+1 );
}
inline bool trie::Del( str s )
{
if( IsNC(s[0]) )
{
--this->CountAp;
if( 0 == this->CountAp && 0 == this->CountSons && root != this )
{
delete this;
return true;
}
return false;
}
int c=s[0]-'a';
--this->CountAp;
if( this->t[c]->Del(s+1) )
{
--this->CountSons;
this->t[c]=NULL;
}
if( 0 == this->CountAp && 0 == this->CountSons && root != this )
{
delete this;
return true;
}
return false;
}
inline int trie::CountWords( str s )
{
if( IsNC(s[0]) )
return this->CountAp;
int c=s[0]-'a';
if( NULL == this->t[c] )
return 0;
return this->t[c]->CountWords(s+1);
}
inline int trie::MaxPrefix( str s, int& l )
{
if( IsNC(s[0]) )
return l;
int c=s[0]-'a';
if( NULL == this->t[c] )
return l;
++l;
return this->t[c]->MaxPrefix( s+1, l );
}
char s[30];
int main(int argc, char** argv)
{
int i;
ifstream in( "trie.in" );
ofstream out( "trie.out" );
root=new trie;
while( in>>i>>s )
{
if( !i )
root->Add(s);
else if( 1 == i )
root->Del(s);
else if( 2 == i )
out<<root->CountWords(s)<<'\n';
else i=0, out<<root->MaxPrefix( s, i )<<'\n';
}
return (EXIT_SUCCESS);
}