Cod sursa(job #1358274)

Utilizator killlerr1Chilom Mircea killlerr1 Data 24 februarie 2015 15:10:10
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <fstream>
#include <cstring>
using namespace std;

const int SIGMA = 26;

ifstream is("trie.in");
ofstream os("trie.out");

struct Node{
    Node()
    {
        nr_cuv = nr_sons = 0;
        memset ( son, 0, sizeof ( son ) );
    }
    int nr_cuv, nr_sons;
    Node* son[SIGMA];
};

Node *T = new Node;

char sir[SIGMA];
int type;

void Insert(Node *nod, char *s)
{
    if( *s == '\0' )
    {
        nod->nr_cuv++;
        return;
    }
    if( nod->son[*s - 'a'] == 0 )
    {
        nod->son[*s - 'a'] = new Node;
        nod->nr_sons++;
    }

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

}

bool Delete( Node *nod, char *s )
{
    if( !nod )
        return false;

    if( *s == 0 )
        nod->nr_cuv--;
    else
        if( Delete(nod->son[*s - 'a'], s+1) )
        {
            nod->son[*s - 'a'] = 0;
            nod->nr_sons--;
        }

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

    return false;

}

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

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

    return 0;
}

int Prefix( Node *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()
{
    while( is >> type >> sir )
    {
        if( type == 0 )
            Insert(T, sir);
        if( type == 1 )
            Delete(T, sir);
        if( type == 2 )
            os << Count(T, sir) << '\n';
        if( type == 3 )
            os << Prefix(T, sir, 0) << '\n';
    }

    is.close();
    os.close();
    return 0;
}