Cod sursa(job #1213240)

Utilizator ZenusTudor Costin Razvan Zenus Data 27 iulie 2014 17:00:52
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.91 kb
#include <cstdio>
#include <cstring>
#include <string>

using namespace std;

#define NMAX 1000

struct Trie
{
    Trie *son[26];
    int terminal;
    int sons;

    Trie()
    {
        sons=0;
        terminal=0;
        memset(son,0,sizeof(son));
    }
};

Trie *T=new Trie;
string str,stringNUL;
int i,N,type;
char S[NMAX];

void Insert(Trie *node,int step)
{
    if (step==str.size())
    {
        node->terminal++;
        return;
    }

    if (!node->son[str[step]-'a'])
    {
        node->son[str[step]-'a']=new Trie();
        node->sons++;
    }

    Insert(node->son[str[step]-'a'],step+1);
}

bool Delete(int step,Trie *node)
{
    if (step==str.size())
    node->terminal--;
    else if (Delete(step+1,node->son[S[step]-'a']))
    {
        node->son[S[step]-'a']=0;
        node->sons--;
    }

    if (!node->terminal && !node->sons && node!=T)
    {
        delete node;
        return true;
    }

    return false;
}

int Query(string S)
{
    int j,t=0;
    Trie *node=T;

    for (j=0;j<S.size();++j)
    {
        if (!node->son[S[j]-'a'])
        return 0;

        node=node->son[S[j]-'a'];
    }

    return node->terminal;
}

int Prefix(Trie *node,int step,int length)
{
    if (step==str.size() || !node->son[str[step]-'a'])
    return length;

    return Prefix(node->son[str[step]-'a'],step+1,length+1);
}

int main()
{
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);

scanf("%d%s",&type,&S);

while (!feof(stdin))
{
    N=strlen(S);
    str=stringNUL;

    for (i=0;i<N;++i)
    str.push_back(S[i]);

    switch(type)
    {
        case 0 : Insert(T,0);
        break;

        case 1 : Delete(0,T);
        break;

        case 2 : printf("%d\n",Query(str));
        break;

        case 3 : printf("%d\n",Prefix(T,0,0));
        break;
    }
    scanf("%d%s",&type,&S);
}

return 0;
}