Cod sursa(job #1053248)

Utilizator Al3ks1002Alex Cociorva Al3ks1002 Data 12 decembrie 2013 16:23:58
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include<cstdio>
#include<cstring>
using namespace std;
int Key,N,Letter;
char Word[25];
struct Trie
{
    int Count,Was;
    Trie *Son[30];
    Trie()
    {
        Count=Was=0;
        memset(Son,0,sizeof(Son));
    }
};
Trie *Root=new Trie;
void Add(Trie *T,int Poz)
{
    if(Poz==N) {T->Count++; return;}
    Letter=Word[Poz]-'a';
    if(!T->Son[Letter]) T->Son[Letter]=new Trie;
    T->Son[Letter]->Was++;
    Add(T->Son[Letter],Poz+1);
}
void Delete(Trie *T,int Poz)
{
    if(Poz==N) {T->Count--; return;}
    Letter=Word[Poz]-'a';
    T->Son[Letter]->Was--;
    Delete(T->Son[Letter],Poz+1);
}
void Count(Trie *T,int Poz)
{
    if(Poz==N) {printf("%d\n",T->Count); return;}
    Letter=Word[Poz]-'a';
    if(!T->Son[Letter] || !T->Son[Letter]->Was) {printf("0\n"); return;}
    Count(T->Son[Letter],Poz+1);
}
void Prefix(Trie *T,int Poz)
{
    if(Poz==N) {printf("%d\n",N); return;}
    Letter=Word[Poz]-'a';
    if(!T->Son[Letter] || !T->Son[Letter]->Was) {printf("%d\n",Poz); return;}
    Prefix(T->Son[Letter],Poz+1);
}
int main()
{
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    while(scanf("%d %s",&Key,Word)+1)
    {
        N=strlen(Word);
        if(Key==0) Add(Root,0);
        else if(Key==1) Delete(Root,0);
        else if(Key==2) Count(Root,0);
        else Prefix(Root,0);
    }
    return 0;
}