Cod sursa(job #2399164)

Utilizator Daria09Florea Daria Daria09 Data 7 aprilie 2019 01:04:48
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <cstdio>
using namespace std;
const int maxword=25;
const int sigma=26;
FILE *f = freopen("trie.in", "r", stdin);
FILE *g = freopen("trie.out", "w", stdout);
struct Trie
{
    Trie *son[sigma];
    short int wordcount,endingcount;
    Trie()
    {
        this->wordcount=this->endingcount=0;
        for(int i=0; i<sigma; ++i)
            this->son[i]=NULL;
    }
};
Trie *root=new Trie;
void Insert(Trie *node,char *word)
{
    node->wordcount++;
    if(*word==NULL)
    {
        node->endingcount++;
        return;
    }
    if(node->son[*word-'a']==NULL)
        node->son[*word-'a']=new Trie;
    Insert(node->son[*word-'a'],word+1);
}
void Erase(Trie *node,char *word)
{
    node->wordcount--;
    if(*word==NULL)
    {
        node->endingcount--;
        return;
    }
    Erase(node->son[*word-'a'],word+1);
}
int CountApparition(Trie *node,char *word)
{
    if(*word==NULL)
        return node->endingcount;
    if(node->son[*word-'a']==NULL)
        return 0;
    return CountApparition(node->son[*word-'a'],word+1);
}
int Prefix(Trie *node,char *word,int ans)
{
    if(*word==NULL||node->son[*word-'a']==NULL||node->son[*word-'a']->wordcount==0)
            return ans;
    return Prefix(node->son[*word-'a'],word+1,ans+1);
}
int main()
{
    char word[maxword];
    int type;
    while(scanf("%d%s", &type, word) == 2)
    {
        if(type==0)
            Insert(root,word);
        else if(type==1)
            Erase(root,word);
        else if(type==2)
             printf("%d\n", CountApparition(root, word));
        else
            printf("%d\n", Prefix(root, word,0));
    }
    return 0;
}