Cod sursa(job #3274849)

Utilizator AlexPlesescuAlexPlesescu AlexPlesescu Data 8 februarie 2025 11:48:19
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb
#include <bits/stdc++.h>

using namespace std;

struct nod {
    int cnt = 0, pre = 0;
    nod * next[30];
} * root;

int cer;
string w;

void add(nod * root, const string &w, int pos = 0) {
    root->pre++;
    if (pos == w.size()) {
        root->cnt++;
        return; /// am ajuns la nod verde
    }
    if (root->next[w[pos] - 'a'] == nullptr) {
        root->next[w[pos] - 'a'] = new nod;
    }
    add(root->next[w[pos] - 'a'], w, pos + 1);
}

void erase(nod * root, const string &w, int pos = 0) {
    root->pre--;
    if (pos == w.size()) {
        /// am ajuns la frunza verde (s a terminat cuvantu)
        root->cnt--; ///
        return;
    }
    erase(root->next[w[pos] - 'a'], w, pos + 1);
    if (root->next[w[pos] - 'a']->pre == 0) {
         delete root->next[w[pos] - 'a'];
         root->next[w[pos] - 'a'] = nullptr;
    }
}

int queryap(nod * root, const string &w, int pos = 0) {
    if (pos == w.size()) {
        return root->cnt;
    } else {
        if (root->next[w[pos] - 'a'] == nullptr)
            return 0;
        return queryap(root->next[w[pos] - 'a'], w, pos + 1);
    }
}

int querylg(nod * root, const string &w, int pos = 0) {
    if (pos == w.size())
        return pos;
    else if (root->next[w[pos] - 'a'] == nullptr)
        return pos;
    else
        return querylg(root->next[w[pos] - 'a'], w, pos + 1);
}


int main() {
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);
    root = new nod;
    while (cin >> cer) {
        cin >> w;
        if (!cer) {
            add(root, w, 0);
        } else if (cer == 1) {
            erase(root, w, 0);
        } else if (cer == 2) {
            cout << queryap(root, w, 0);
        } else if (cer == 3) {
            cout << querylg(root, w, 0);
        }
    }
}