Cod sursa(job #2553607)

Utilizator Mirela_MagdalenaCatrina Mirela Mirela_Magdalena Data 22 februarie 2020 10:27:58
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <cstring>
#include <fstream>
using namespace std;

ifstream f("trie.in");
ofstream g("trie.out");

struct nod{
    int fin = 0;
    int nrc = 0;

    nod *urm[30]{0};
}*root;

int type, l, last;
char cuv[30];

void add(nod *&p, int index)
{
    if(index == l)
    {
        p->fin ++;
        return;
    }
    if(!p->urm[cuv[index]-'a'])
    {
        p->urm[cuv[index]-'a'] = new nod;
    }
    p->urm[cuv[index]-'a']->nrc++;
    add(p->urm[cuv[index]-'a'], index+1);

}
bool ok = 1;
void del(nod *&p, int index)
{
    if(index == l)
    {
        p->fin --;
        if(p->fin == 0 && p->nrc == 0)
        {
            p = 0;
            delete p;
        }
        return;
    }
    p->urm[cuv[index]-'a']->nrc--;
    del(p->urm[cuv[index]-'a'], index+1);
    if(p->fin == 0 && p->nrc == 0 && p != root)
    {
        p = 0;
        delete p;
    }
}

void fr(nod *p, int index)
{
    if(index == l)
    {
        g<<p->fin<<'\n';
        return;
    }
    if(!p->urm[cuv[index]-'a'])
    {
        g<<"0\n";
        return;
    }
    fr(p->urm[cuv[index]-'a'], index+1);
}

int pref(nod *p, int index)
{
    if(index == l)
        return l;
    if(!p->urm[cuv[index]-'a'] || p->urm[cuv[index]-'a']->nrc == 0)
        return index;
    return pref(p->urm[cuv[index]-'a'], index+1);
}

int main()
{
    root = new nod;
    while(f>>type>>cuv)
    {
        l = strlen(cuv);
        if(type == 0)
            add(root, 0);
        else if(type == 1)
            del(root, 0);
        else if(type == 2)
            fr(root, 0);
        else{
            g<<pref(root, 0)<<'\n';
        }

    }
    return 0;
}