Pagini recente » Cod sursa (job #320963) | Cod sursa (job #67314) | Cod sursa (job #1554124) | Cod sursa (job #2517809) | Cod sursa (job #582363)
Cod sursa(job #582363)
#include <string>
#include <fstream>
#include <cstdlib>
#define N_MAX
using namespace std;
class Trie
{
int countSet;
int countApp;
Trie* isSet[31];
public :
Trie() : countSet(0), countApp(0)
{
for( int i=0; i < 31; ++i )
isSet[i]=NULL;
}
void Add( string::const_iterator it, string::const_iterator iend )
{
if( it >= iend )
{
++countApp;
return;
}
int x=*it-'a';
if( !isSet[x] )
isSet[x]=new Trie(), ++countSet;
isSet[x]->Add( it+1, iend );
}
bool Delete( string::const_iterator it, string::const_iterator iend )
{
if( it >= iend )
{
--countApp;
if( countApp < 0 )
countApp=0;
if( 0 == countApp && 0 == countSet )
{
delete this;
return true;
}
return false;
}
int x=*it-'a';
if( !isSet[x] ) //this should never happen
{
return 0 == countSet;
}
if( isSet[x]->Delete( it+1, iend ) ) //can delete this node
{
isSet[x]=NULL;
--countSet;
}
if( 0 == countSet )
{
delete this;
return true;
}
return false;
}
int CountApp( string::const_iterator it, string::const_iterator iend )
{
if( it >= iend )
return countApp;
int x=*it-'a';
if( !isSet[x] )
return 0;
return isSet[x]->CountApp( it+1, iend );
}
int LCP( string::const_iterator it, string::const_iterator iend )
{
if( it >= iend )
return 0;
int x=*it-'a';
if( !isSet[x] )
return 0;
return isSet[x]->LCP( it+1, iend )+1;
}
} *r=new Trie();
int main( void )
{
int op;
string s;
ifstream in( "trie.in" );
ofstream out( "trie.out" );
while( in>>op>>s )
{
switch( op )
{
case 0 : r->Add( s.begin(), s.end() ); break;
case 1 : r->Delete( s.begin(), s.end() ); break;
case 2 : out<<r->CountApp( s.begin(), s.end() )<<'\n'; break;
case 3 : out<<r->LCP( s.begin(), s.end() )<<'\n'; break;
}
}
return EXIT_SUCCESS;
}