Cod sursa(job #2753005)

Utilizator George_CristianGeorge Dan-Cristian George_Cristian Data 20 mai 2021 18:03:43
Problema Trie Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <cstring>

using namespace std;

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

struct trie {
    int ap, appre;
    trie *copii[26];

    trie() {
        ap = 0;
        for (auto &i : copii)
            i = nullptr;
    }
} *rad;

int op;
char cuv[25], nrl;

void adaugare(trie *rad, int poz) {
    rad->appre++;
    if (poz == nrl) {
        rad->ap++;
        return;
    }
    if (!rad->copii[cuv[poz] - 'a'])
        rad->copii[cuv[poz] - 'a'] = new trie();
    adaugare(rad->copii[cuv[poz] - 'a'], poz + 1);
}

void stergere(trie *rad, int poz) {
    rad->appre--;
    if (poz == nrl) {
        rad->ap--;
        return;
    }
    stergere(rad->copii[cuv[poz] - 'a'], poz + 1);
}

int nrap(trie *rad, int poz) {
    if (!rad || !rad->appre)
        return 0;
    if (poz == nrl)
        return rad->ap;
    return nrap(rad->copii[cuv[poz] - 'a'], poz + 1);
}

int cmlpc(trie *rad, int poz) {
    if (!rad || !rad->appre)
        return poz - 1;
    if (poz == nrl)
        return poz - 1;
    return cmlpc(rad->copii[cuv[poz] - 'a'], poz + 1);
}

int main() {
    rad = new trie();
    while (f >> op >> cuv) {
        nrl = strlen(cuv);
        if (op == 0)
            adaugare(rad, 0);
        else if (op == 1)
            stergere(rad, 0);
        else if (op == 2)
            g << nrap(rad, 0) << '\n';
        else
            g << cmlpc(rad, 0) << '\n';
    }
    return 0;
}