Pagini recente » Cod sursa (job #2034738) | Cod sursa (job #61196) | Cod sursa (job #2884643) | Cod sursa (job #981729) | Cod sursa (job #615635)
Cod sursa(job #615635)
#include <string>
#include <fstream>
#include <cstdlib>
#define N_MAX
using namespace std;
class Trie
{
Trie *v[31];
int countSons, countApp;
bool Delet( string::const_iterator it, const string::const_iterator& iend );
public :
Trie() : countSons(0), countApp(0)
{
for( int i=0; i < 31; ++i )
v[i]=NULL;
}
void Add( string::const_iterator it, const string::const_iterator& iend );
void Delete( string::const_iterator it, const string::const_iterator& iend );
int GetApp( string::const_iterator it, const string::const_iterator& iend );
int GetLongestPrefix( string::const_iterator it, const string::const_iterator& iend );
} *root=new Trie();
void Trie::Add( string::const_iterator it, const string::const_iterator& iend )
{
if( it >= iend )
++countApp;
else {
int cIndex=*it-'a';
if( NULL == v[cIndex] )
v[cIndex]=new Trie(), ++countSons;
v[cIndex]->Add( it+1, iend );
}
}
bool Trie::Delet( string::const_iterator it, const string::const_iterator& iend )
{
if( it >= iend )
{
--countApp;
if( countApp <= 0 )
{
countApp=0;
if( 0 == countSons )
return true;
}
return false;
}
int cIndex=*it-'a';
if( NULL == v[cIndex] ) //this should not happen, normaly nothing should happen
exit(1);
if( v[cIndex]->Delet( it+1, iend ) )
v[cIndex]=NULL, --countSons;
if( this != root && 0 == countSons && 0 == countApp )
{
delete this;
return true;
}
return false;
}
void Trie::Delete( string::const_iterator it, const string::const_iterator& iend )
{
Delet( it, iend );
}
int Trie::GetApp( string::const_iterator it, const string::const_iterator& iend )
{
if( it >= iend )
return countApp;
else {
int cIndex=*it-'a';
if( NULL == v[cIndex] )
return 0;
return v[cIndex]->GetApp( it+1, iend );
}
}
int Trie::GetLongestPrefix( string::const_iterator it, const string::const_iterator& iend )
{
if( it >= iend )
return 0;
else {
int cIndex=*it-'a';
if( NULL == v[cIndex] )
return 0;
return 1+v[cIndex]->GetLongestPrefix( it+1, iend );
}
}
int main( void )
{
int op;
string s;
ifstream in( "trie.in" );
ofstream out( "trie.out" );
while( in>>op>>s )
{
switch(op)
{
case 0 : root->Add( s.begin(), s.end() ); break;
case 1 : root->Delete( s.begin(), s.end() ); break;
case 2 : out<<root->GetApp( s.begin(), s.end() )<<'\n'; break;
case 3 : out<<root->GetLongestPrefix( s.begin(), s.end() )<<'\n';
}
}
return EXIT_SUCCESS;
}