Cod sursa(job #3166418)

Utilizator Xutzu358Ignat Alex Xutzu358 Data 8 noiembrie 2023 18:52:19
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.15 kb
#include <bits/stdc++.h>
using namespace std;

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

struct nod{
    nod *fiu[26]; /// 26 pointeri - fiecare reprezentand cate o litera
    int nr_fii;
    int nr_ap;
    nod() { /// constructor - aceste instructiuni se executa la crearea unui nod nou
        fill(fiu, fiu+26, nullptr); /// sau cu un for (sa punem nullptr sau 0 in fiu[0->25])
        nr_fii = 0;
        nr_ap = 0;
    }
};

nod *root = new nod; /// radacina retine defapt ""
string w;
int op;
bool ok=0;
int max_pref;

void adds(nod *x, int pos) {
    if (pos==w.size()) {
        x->nr_ap++;
        return;
    }
    /// w[pos] = a pos-a litera din cuvant (cea la care trebuie sa mergem)
    /// fiu[w[pos]-'a'] = pointer-ul corespunzator catre acea litera
    if (x->fiu[w[pos]-'a'] == nullptr) {
        x->fiu[w[pos]-'a'] = new nod;
        x->nr_fii++;
    }
    adds(x->fiu[w[pos]-'a'], pos+1);
}

bool memory_delete(nod *x) {
    if (x->nr_ap==0 && x->nr_fii==0 && x!=root) {
        delete x;
        return 1; /// am sters nodul
    }
    return 0; /// nu am sters nodul din memorie
}

void deletes(nod *x, int pos) {
    if (pos==w.size()) {
        x->nr_ap--;
        ok = memory_delete(x);
        return;
    }
    deletes(x->fiu[w[pos]-'a'], pos+1);
    if (ok == 1) {
        x->fiu[w[pos]-'a'] = nullptr;
        x->nr_fii--;
    }
    ok = memory_delete(x);
}

int appears(nod *x, int pos) {
    if (pos==w.size()) return x->nr_ap;
    else if (x->fiu[w[pos]-'a'] != nullptr) {
        return appears(x->fiu[w[pos]-'a'], pos+1);
    }
    return 0;
}

int common_prefix(nod *x, int pos) {
    if (x->fiu[w[pos]-'a'] == nullptr || pos == w.size()) {
        return pos;
    }
    return common_prefix(x->fiu[w[pos]-'a'], pos+1);
}

int main()
{
    while (f >> op) {
        f >> w;
        if (op==0) {
            adds(root, 0);
        }
        else if (op==1) {
            deletes(root, 0);
        }
        else if (op==2) {
            g << appears(root, 0) << '\n';
        }
        else {
            g << common_prefix(root, 0) << '\n';
        }
    }
    return 0;
}