Cod sursa(job #582367)

Utilizator BitOneSAlexandru BitOne Data 15 aprilie 2011 11:43:10
Problema Trie Scor 55
Compilator cpp Status done
Runda Arhiva educationala Marime 2.37 kb
#include <string>
#include <fstream>
#include <cstdlib>
#define N_MAX

using namespace std;
class Trie
{
   bool root;
   int countSet;
   int countApp;
   Trie* isSet[31];
public :
   Trie() : countSet(0), countApp(0), root(true)
   {
       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(), isSet[x]->root=false, ++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( !root && 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;
}