Pagini recente » Cod sursa (job #602320) | Cod sursa (job #545557) | Cod sursa (job #54209) | Cod sursa (job #3175287) | Cod sursa (job #545555)
Cod sursa(job #545555)
#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() : root(true), _countSetLetters(0), _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 )
{
--_countApp;
if( 0 == _countApp && 0 == _countSetLetters )
return true;
return false;
}
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;
}