Cod sursa(job #1585585)

Utilizator cristian.caldareaCaldarea Cristian Daniel cristian.caldarea Data 31 ianuarie 2016 11:38:19
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstring>
using namespace std;

ifstream fin("trie.in");
ofstream fout("trie.out");

const int Dim = 26;

struct Nod
{
    Nod()
    {
        nr_c = nr_s = 0;
        memset(son, 0, sizeof (son) );
    }
    int nr_c, nr_s;
    Nod* son[Dim];
};

char cuv[Dim];
Nod *T = new Nod;

void Read();
void Insert( Nod* nod, char *s);
bool Del( Nod* nod, char *s);
int Count( Nod* nod, char *s);
int Pref( Nod* nod, char *s, int nv);


int main()
{
    Read();
    fin.close();
    fout.close();
    return 0;
}
void Read()
{
    int x;
    while( fin >> x )
    {
        fin.get();
        fin.getline(cuv, 21);

        switch (x)
        {
            case 0 : Insert( T, cuv );                    break;
            case 1 : Del( T, cuv );                       break;
            case 2 : fout << Count( T, cuv ) << '\n';     break;
            case 3 : fout << Pref( T, cuv, 0 ) << '\n';   break;
        }
    }
}

void Insert( Nod* nod, char *s)
{
    if ( *s == '\0' )
    {
        nod->nr_c++;
        return;
    }

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

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

bool Del( Nod* nod, char *s)
{
    if ( *s == '\0' )
        nod->nr_c--;
    else
        if ( Del( nod->son[*s - 'a'], s + 1) )
        {
            nod->son[*s - 'a'] = 0;
            nod->nr_s --;
        }

    if ( nod->nr_c == 0 && nod->nr_s == 0 && nod != T )
    {
        delete nod;
        return true;
    }

    return false;
}

int Count( Nod* nod, char *s)
{
    if ( *s == '\0' )
        return nod->nr_c;

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

int Pref( Nod* nod, char *s, int nv)
{
    if ( *s == '\0' || nod->son[*s - 'a'] == 0 )
        return nv;

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