Cod sursa(job #997510)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 14 septembrie 2013 12:53:12
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.99 kb
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

const int Sigma = 26;

class Trie
{
    public:

        Trie()
        {
            cont = nr_sons = 0;
            memset ( son, 0, sizeof ( son ) );
        }

        int cont, nr_sons;
        Trie *son[Sigma];
};

Trie *T = new Trie;
char sir[Sigma];
int tip;

void inserare( Trie *nod, char *s )
{
    if ( *s == '\0' )
    {
        nod->cont++;
        return;
    }

    if ( nod->son[ *s - 'a' ] == 0 )
    {
        nod->son[ *s - 'a' ] = new Trie;
        nod->nr_sons++;
    }

    inserare( nod->son[ *s - 'a' ], s + 1 );
}

int sterge( Trie *nod, char *s )
{
    if ( *s == '\0' )
    {
        nod->cont--;
    }
    else
        if ( sterge( nod->son[ *s - 'a' ], s + 1 ) )
        {
            nod->son[ *s - 'a' ] = 0;
            nod->nr_sons--;
        }

    if ( nod->cont == 0 && nod->nr_sons == 0 && nod != T )
    {
        delete nod;
        return 1;
    }

    return 0;
}

int numara( Trie *nod, char *s )
{
    if ( *s == '\0' )
    {
        return nod->cont;
    }

    if ( nod->son[ *s - 'a' ] )
            return numara( nod->son[ *s - 'a' ], s + 1 );

    return 0;
}

int prefix( Trie *nod, char *s, int k )
{
    if ( *s == '\0' || nod->son[ *s - 'a' ] == 0 )
    {
        return k;
    }

    return prefix( nod->son[ *s - 'a' ], s + 1, k + 1 );
}

int main()
{
    ifstream f("trie.in");
    ofstream g("trie.out");

    while ( f.getline( sir, Sigma ) )
    {
        switch ( sir[0] )
        {
            case '0': inserare( T, sir + 2 );                   break;
            case '1': sterge( T, sir + 2 );                     break;
            case '2': g << numara( T, sir + 2    ) << "\n";     break;
            case '3': g << prefix( T, sir + 2, 0 ) << "\n";     break;

            default: cout << "Eroare!\n";   break;
        }
    }

    f.close();
    g.close();

    return 0;
}