Cod sursa(job #3370340)

Utilizator daviddxmqStan David Andrei daviddxmq Data 25 octombrie 2026 17:12:05
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <iostream>
#include <cstdio>

using namespace std;

const int MAXN = 600005;

int trie[MAXN][26];
int nrCuv[MAXN];
int nrAparitii[MAXN];
int nodCurent = 0;

void insereaza(char s[]) {
    int nod = 0;
    ++nrAparitii[nod];
    for (int i = 0; s[i] != '\0'; ++i) {
        int c = s[i] - 'a';
        if (!trie[nod][c])
            trie[nod][c] = ++nodCurent;
        nod = trie[nod][c];
        ++nrAparitii[nod];
    }
    ++nrCuv[nod];
}

void sterge(char s[]) {
    int nod = 0;
    --nrAparitii[nod];
    for (int i = 0; s[i] != '\0'; ++i) {
        int c = s[i] - 'a';
        int nodUrmator = trie[nod][c];
        --nrAparitii[nodUrmator];
        if (!nrAparitii[nodUrmator]) {
            trie[nod][c] = 0;
            return;
        }
        nod = nodUrmator;
    }
    --nrCuv[nod];
}

int numara(char s[]) {
    int nod = 0;
    for (int i = 0; s[i] != '\0'; ++i) {
        int c = s[i] - 'a';
        if (!trie[nod][c])
            return 0;
        nod = trie[nod][c];
    }
    return nrCuv[nod];
}

int lcp(char s[]) {
    int nod = 0;
    int lungime = 0;
    for (int i = 0; s[i] != '\0'; ++i) {
        int c = s[i] - 'a';
        if (!trie[nod][c] || !nrAparitii[trie[nod][c]])
            break;
        nod = trie[nod][c];
        ++lungime;
    }
    return lungime;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);
    int op;
    char s[25];
    while (cin >> op >> s)
        if (op == 0)
            insereaza(s);
        else if (op == 1)
            sterge(s);
        else if (op == 2)
            cout << numara(s) << "\n";
        else if (op == 3)
            cout << lcp(s) << "\n";
    return 0;
}