Cod sursa(job #3033069)

Utilizator Robert_MitriRobert Mitri Robert_Mitri Data 23 martie 2023 12:10:59
Problema Trie Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.35 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]=0;
        }
    }
};
struct trie
{
    nod root;

    void add(char* q)
    {
        int p=0;
        nod* act = &root;
        while(q[p]!=0)
        {
            if(act->childs[q[p]-'a']==NULL)
            {
                act->childs[q[p]-'a']=new nod;
                act->nri++;
            }
            act=act->childs[q[p]-'a'];
            p++;
            if(!q[p])
            {
                act->nrf++;

            }
        }
    }
    int numar_ap(char *q)
    {
        int p=0;
        nod* act = &root;
        while(q[p]!=0)
        {

            if(act->childs[q[p]-'a']==NULL)
            {
                return 0;
            }

            act=act->childs[q[p]-'a'];
            p++;
            if(!q[p])
            {
                return act->nrf;
            }
        }
    }
    int l_prefix(char *q)
    {
        int l=0;
        int p=0;
        nod* act = &root;
        while(q[p]!=0)
        {
            if(act->childs[q[p]-'a']==NULL)
            {
                return l;
            }
            act=act->childs[q[p]-'a'];
            p++;
            if(!q[p])
            {
                return l;
            }

            l++;
        }
    }
    int sterge(nod* act ,char *q)
    {

        if(*q==0)
        {
            act->nrf--;
        }
        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);
        }
        else if (op=='2')
        {
            fout<<a.numar_ap(p)<<'\n';
        }
        else if (op=='3')
        {
            fout<<a.l_prefix(p)<<'\n';
        }
        else
        {
            a.sterge(&a.root,p);
        }
    }
}