Cod sursa(job #3206151)

Utilizator MegaCoderMinoiu Teodor Mihai MegaCoder Data 21 februarie 2024 19:00:12
Problema Trie Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include<fstream>
std::ifstream fin("trie.in");
std::ofstream fout("trie.out");
struct node{
    int nrC=0;
    int nrAp=0;
    node *a[27];

    node()
    {
        nrC=0;
        nrAp=0;
        for(int i=0; i<27; ++i)
            a[i]=NULL;
    }
}*rad=new node;
void inserare(node *t, char *pos)
{
    if(*pos==0)
    {
        t->nrAp++;
        return;
    }
    int i=*pos-'a';
    if(!(t->a[i]))
    {
        t->a[i]=new node;
        t->nrC++;
    }
    inserare(t->a[i], pos+1);
}
bool stergere(node *t, char *pos)
{
    if(*pos==0)
    {
        t->nrAp--;
        if(t->nrAp==0 && t->nrC==0 && t!=rad)
        {
            delete t;
            return true;
        }
        return false;
    }
    int i=*pos-'a';
    bool del=stergere(t->a[i], pos+1);
    if(del)
    {
        t->a[i]=0;
        t->nrC--;
        if(t->nrAp==0 && t->nrC==0 && t!=rad && del)
        {
            delete t;
            return true;
        }
    }
    return false;
}
int ap(node *t, char *cuvant)
{
    if(*cuvant==0)
        return t->nrAp;
    int i=*cuvant-'a';
    if(t->a[i])
       return ap(t->a[i], cuvant+1);
    return 0;
}
int pref(node *t, char *cuvant, int nr)
{
    if(*cuvant==0)
        return nr;
    int i=*cuvant-'a';
    if(t->a[i]==0)
        return nr;
    return pref(t->a[i], cuvant+1, nr+1);
}

int main()
{
    while(!fin.eof())
    {
        int task;
        char s[25];
        fin>>task>>s;
        if(!task)
            inserare(rad, s);
        else if(task==1)
            stergere(rad, s);
        else if(task==2)
            fout<<ap(rad, s)<<'\n';
        else
            fout<<pref(rad, s, 0)<<'\n';
    }
    return 0;
}