Cod sursa(job #3305304)

Utilizator paulihno15Ciumandru Paul paulihno15 Data 31 iulie 2025 16:35:40
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.88 kb
#include <bits/stdc++.h>
#define NMAX 100000
#define MMAX 18
#define MOD 666013

using namespace std;

ifstream fin("trie.in");
ofstream fout("trie.out");

string linie;

struct Trie_Node {
    Trie_Node *des[26];
    int cnt, prf_cnt;

    Trie_Node() {
        for (int i = 0; i < 26; i++) {
            des[i] = NULL;
        }
        cnt = prf_cnt = 0;
    }
};

Trie_Node *rad = new Trie_Node();

void insert(const string &cuv) {
    Trie_Node *p = rad;
    for (char ch : cuv) {
        int ind = ch - 'a';
        if (!p -> des[ind]) {
            p -> des[ind] = new Trie_Node();
        }
        p = p -> des[ind];
        p -> prf_cnt++;
    }
    p -> cnt++;
}

void remove(const string &cuv) {
    Trie_Node *p = rad;
    for (char ch : cuv) {
        int ind = ch - 'a';
        Trie_Node *des_p = p -> des[ind];
        des_p -> prf_cnt--;
        p = des_p;
    }
    p -> cnt--;
}

int cnt_cuv(const string &cuv) {
    Trie_Node *p = rad;
    for (char ch : cuv) {
        int ind = ch - 'a';
        if (!p -> des[ind]) {
            return 0;
        }
        p = p -> des[ind];
    }
    return p -> cnt;
}

int prf_max(const string &cuv) {
    Trie_Node *p = rad;
    int lg = 0;
    for (char ch : cuv) {
        int ind = ch - 'a';
        if (!p -> des[ind]) {
            break;
        }
        p = p -> des[ind];
        if (!p -> prf_cnt) {
            break;
        }
        lg++;
    }
    return lg;
}

int main() {
    ios_base::sync_with_stdio(false);
    fin.tie(NULL);
    fout.tie(NULL);

    while (getline(fin, linie)) {
        int op = linie[0] - '0';
        string cuv = linie.substr(2);
        if (op == 0) {
            insert(cuv);
        }
        else if (op == 1) {
            remove(cuv);
        }
        else if (op == 2) {
            fout << cnt_cuv(cuv) << '\n';
        }
        else {
            fout << prf_max(cuv) << '\n';
        }
    }
    return 0;
}