Cod sursa(job #3037687)

Utilizator Robert_MitriRobert Mitri Robert_Mitri Data 26 martie 2023 10:10:39
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.04 kb
#include <fstream>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");

struct nod
{
    int nri;
    int nrf;
    nod* childs[30]= {0};

    nod()
    {
        nri=0;
        nrf=0;
        for(int i=0;i<=29;i++)
        {
            childs[i]=NULL;
        }
    }
};
struct trie
{
    nod root;
    void add(char* q,nod* act)
    {
        if(*q !=0)
        {
            if(act->childs[*q-'a']==NULL)
            {
                act->childs[*q-'a']=new nod;
                act->nri++;
            }
            add(q+1,act->childs[*q-'a']);

        }
        else
        act->nrf++;

    }
    int numar_ap(char *q,nod*act)
    {
        if(*q != 0)
        {
            if(act->childs[*q-'a']==NULL)
                return 0;
            return numar_ap(q+1,act->childs[*q-'a']);
        }
        return act->nrf;

    }
    int l_prefix(char *q,nod* act)
    {
        if(*q != 0)
        {
            if(act->childs[*q-'a']==NULL)
                return 0;
            return 1 +l_prefix(q+1,act->childs[*q-'a']);
        }
        return 0;
    }
    int sterge(nod* act ,char *q)
    {

        if(*q==0)
        {
            act->nrf--;
        }
        else if (act->childs[*q-'a']==NULL)
            return 0;
        else if (sterge(act->childs[*q-'a'],q+1))
        {
            act->childs[*q-'a']=0;
            act->nri--;

        }
        if(act->nrf==0  && act->nri==0 && act!=&root)
        {
            delete act;
            return 1;
        }
        return 0;
    }


}a;

char s[50];

int main()
{
    while(fin.getline(s,49))
    {
        char op = s[0];
        char *p = s+2;
        if(op=='0')
        {
            a.add(p,&a.root);
        }
        else if (op=='2')
        {
            fout<<a.numar_ap(p,&a.root)<<'\n';
        }
        else if (op=='3')
        {
            fout<<a.l_prefix(p,&a.root)<<'\n';
        }
        else
        {
            a.sterge(&a.root,p);
        }
    }
}