Cod sursa(job #2759482)

Utilizator TudorNicorescuNicorescu Tudor TudorNicorescu Data 18 iunie 2021 10:20:52
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <fstream>
using namespace std;
const int NL=26;
const int L=21;

struct nod
{
    nod* fii[NL];
    int nr_cuv, nr_pref;

    nod()
    {
        for (int i = 0; i < NL; i++)
        {
            fii[i] = NULL;
        }
        nr_cuv = 0;
        nr_pref = 0;
    }
};

nod* adauga(nod* p, char* s)
{
    if (p == NULL)
    {
        p = new nod();
    }
    p->nr_pref++;
    if (s[0] == '\0')
    {
        p->nr_cuv++;
    }
    else
    {
        p->fii[s[0]- 'a'] = adauga(p->fii[s[0]- 'a'], s + 1);
    }
    return p;
}

nod* sterge(nod* p, char* s)
{
    if (s[0] == '\0')
    {
        p->nr_cuv--;
    }
    else
    {
        p->fii[s[0] - 'a'] = sterge(p->fii[s[0] - 'a'], s + 1);
    }
    p->nr_pref--;
    if (p->nr_pref == 0)
    {
        delete p;
        return NULL;
    }
    return p;
}

int nr_cuvinte(nod* p, char* s)
{
    if (p == NULL)
    {
        return 0;
    }
    if (s[0] == '\0')
    {
        return p->nr_cuv;
    }
    return nr_cuvinte(p->fii[s[0]- 'a'], s + 1);
}

int lungime_pref(nod* p, char* s)
{
    if (s[0] == '\0')
    {
        return 0;
    }
    if (p->fii[s[0]- 'a'] == NULL)
    {
        return 0;
    }
    return 1 + lungime_pref(p->fii[s[0]- 'a'], s + 1);
}

int main()
{
    ifstream in("trie.in");
    ofstream out("trie.out");
    char s[L];
    int tip;
    nod *r = NULL;
    while (in >> tip >> s)
    {
        if (tip == 0)
        {
            r = adauga(r, s);
        }
        if (tip == 1)
        {
            r = sterge(r, s);
        }
        if (tip == 2)
        {
             out << nr_cuvinte(r, s) << "\n";
        }
        if (tip == 3)
        {
            out << lungime_pref(r, s) << "\n";
        }
    }
     in.close();
    out.close();
    return 0;
}