Cod sursa(job #1213234)

Utilizator ZenusTudor Costin Razvan Zenus Data 27 iulie 2014 16:31:34
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 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(string S)
{
    int j;
    Trie *node=T;

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

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

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)
    node=node->son[S[j]-'a'];

    return node->terminal;
}

int Prefix(string S)
{
    Trie *node=T;
    int j;

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

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

    return j;
}


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(str);
        break;

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

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

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

return 0;
}