Cod sursa(job #450173)

Utilizator alexandru92alexandru alexandru92 Data 7 mai 2010 21:25:42
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
/* 
 * File:   main.cpp
 * Author: virtualdemon
 *
 * Created on May 7, 2010, 8:20 PM
 */
#include <cstdlib>
#include <fstream>
#define oo 0x3f3f3f3f

/*
 * 
 */
using namespace std;
typedef char* str;
struct trie
{
    trie* t[30];
    int CountWord, CountSons;
    trie( void ) : CountWord(0), CountSons(0)
    {
        for( int i=0; i <= 29; ++i )
            t[i]=NULL;
    }
} *root;
typedef trie* tt;
inline bool IsNC( char x )
{
    return  x < 'a' || x > 'z';
}
inline void Add( tt& r, str s )
{
    if( IsNC(s[0]) )
    {
        ++r->CountWord;
        return;
    }
    int c=s[0]-'a';
    if( NULL == r->t[c] )
        r->t[c]=new trie, ++r->CountSons;
    Add( r->t[c], s+1 );
}
inline int CountWords( tt r, str s )
{
    if( IsNC(s[0]) )
        return r->CountWord;
    int c=s[0]-'a';
    if( NULL == r->t[c]  )
        return 0;
    return CountWords( r->t[c], s+1 );
}
inline void LongestPrefix( tt r, str s, int& l )
{
    if( IsNC(s[0]) )
        return;
    int c=s[0]-'a';
    if( NULL == r->t[c] )
        return;
    ++l;
    LongestPrefix( r->t[c], s+1, l );
}
inline void Delete( tt& r, str s )
{
    if( IsNC(s[0]) )
       return;
    int c=s[0]-'a';
    if( NULL == r->t[c] )
        return;
    --r->t[c]->CountWord;
    Delete( r->t[c], s+1 );
    if( 0 == r->t[c]->CountSons )
    {
        --r->CountSons;
        delete r->t[c];
        r->t[c]=NULL;
    }

}
char ss[30];
int main( void )
{
    int i;
    ifstream in( "trie.in" );
    ofstream out( "trie.out" );
    root=new trie;
    while( in>>i>>ss )
    {
        if( !i )
            Add( root, ss );
        else if( 1 == i )
                Delete( root, ss );
            else if( 2 == i )
                    out<<CountWords( root, ss )<<'\n';
                 else i=0, LongestPrefix( root, ss, i ), out<<i<<'\n';
    }
    return EXIT_SUCCESS;
}