Cod sursa(job #3215691)

Utilizator DomnulMilandruMilandru Nicon-David DomnulMilandru Data 15 martie 2024 11:52:36
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.08 kb

#include <fstream>
using namespace std;
ifstream cin("trie.in");
ofstream cout("trie.out");
struct node{
    node *a[27];
    int nrap=0;
    int copii=0;
    node ()
    {
        copii=0;
        nrap=0;
        for(int i=0;i<27;i++)
           a[i]=NULL;
    }
}*rad=new node;
void adaugare(node *t,char *cuvant)
{
    if(*cuvant==0)
    {
        t->nrap++;
        return;
    }
    int alfabet=*cuvant-'a';
    if(!t->a[alfabet])
    {
        t->a[alfabet]=new node;
        t->copii++;
    }
    adaugare(t->a[alfabet],cuvant+1);
}
int ap(node *t,char *cuvant)
{
    if(*cuvant==0)
       return t->nrap;
    int alfabet=*cuvant-'a';
    if(t->a[alfabet])
       return ap(t->a[alfabet],cuvant+1);
    return 0;
}
int prefix(node *t,char *cuvant,int nivel)
{
    if(*cuvant==0)
       return nivel;
    int alfabet=*cuvant-'a';
    if(t->a[alfabet]==0)
        return nivel;
    else
      return prefix(t->a[alfabet],cuvant+1,nivel+1);
}
bool stergere(node *t,char *cuvant)
{
    if(*cuvant==0)
    {
        t->nrap--;
        if(!(t->nrap) && !(t->copii) && t!=rad)
           {
               delete t;
               return 1;
           }
        return 0;
    }
    int alfabet=*cuvant-'a';
    bool ok=stergere(t->a[alfabet],cuvant+1);
    if(ok)
    {
        t->copii--;
        t->a[alfabet]=0;
        if(!(t->nrap) && !(t->copii) && t!=rad)
           {
               delete t;
               return 1;
           }
        return 0;
    }
    return 0;
}
int x;
char s[21];
int main()
{
    while(cin>>x)
    {
        cin>>s;
        switch (x)
        {
            case 0:
            {
                adaugare(rad,s);
                break;
            }
            case 1:
            {
                stergere(rad,s);
                break;
            }
            case 2:
            {
                cout<<ap(rad,s)<<'\n';
                break;
            }
            case 3:
            {
                cout<<prefix(rad,s,0)<<'\n';
            }
        }
    }

    return 0;
}