Cod sursa(job #3340403)

Utilizator Alex_at_gameIustin-Alexandru Frateanu Alex_at_game Data 14 februarie 2026 10:18:11
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.04 kb
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned ll;
using ld = long double;
#define all(v) begin(v), end(v)
#define al(v, l, r) begin(v) + l, begin(v) + r + 1
#define pb push_back
#define pob pop_back
#define sz(v) (int)v.size()
#define fs first
#define sd second

constexpr int inf = 2e9;
constexpr ll infll = 4e18;

struct trie_nod {
    unordered_map<char, int> mp;
    int cnt, nr; ///cnt -> numarul de cuvinte ce se termina in acel nod ; nr -> numarul de cuvinte din care face parte
};

vector<trie_nod> v{1};

void insert(const string& s) {
    int nod = 0;
    for (char c : s) {
        if (!v[nod].mp.count(c)) {
            v[nod].mp[c] = sz(v);
            v.emplace_back();
        }

        nod = v[nod].mp[c];
        v[nod].nr++;
    }

    v[nod].cnt++;
}

void erase(const string& s) {
    int nod = 0;
    for (char c : s) {
        nod = v[nod].mp[c];
        v[nod].nr--;
    }

    v[nod].cnt--;
    nod = 0;

    for (char c : s) {
        if (!v[v[nod].mp[c]].nr) {
            v[nod].mp.erase(c);
            return;
        }

        nod = v[nod].mp[c];
    }
}

int count(const string& s) {
    int nod = 0;
    for (char c : s) {
        if (!v[nod].mp.count(c)) {
            return 0;
        }

        nod = v[nod].mp[c];
    }

    return v[nod].cnt;
}

int lcp(const string& s) {
    int nod = 0, lg = 0;
    for (char c : s) {
        if (!v[nod].mp.count(c)) {
            return lg;
        }

        nod = v[nod].mp[c];
        lg++;
    }

    return lg;
}

signed main() {
    ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);

    int t;
    string s;

    while (cin >> t >> s) {
        if (t == 0) {
            insert(s);
        } else if (t == 1) {
            erase(s);
        } else if (t == 2) {
            cout << count(s) << "\n";
        } else {
            cout << lcp(s) << "\n";
        }
    }
}