Cod sursa(job #3313662)

Utilizator stefanvoicaVoica Stefan stefanvoica Data 5 octombrie 2025 19:26:38
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.9 kb
#include <bits/stdc++.h>
using namespace std;

static inline int lcp(const string& s1, const string& s2) {
    size_t n = min(s1.size(), s2.size());
    size_t i = 0;
    while (i < n && s1[i] == s2[i]) ++i;
    return static_cast<int>(i);
}

int main() {
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);

    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    unordered_map<string, int> counts;
    counts.reserve(131072);
    counts.max_load_factor(0.7f);

    set<string> words;

    int tip;
    string w;

    while (cin >> tip >> w) {
        switch (tip) {
            case 0: {
                int& c = counts[w];
                if (c == 0) words.insert(w);
                ++c;
                break;
            }
            case 1: {
                auto it = counts.find(w);
                if (it != counts.end() && it->second > 0) {
                    --(it->second);
                    if (it->second == 0) {
                        words.erase(w);
                        counts.erase(it);
                    }
                }
                break;
            }
            case 2: {
                auto it = counts.find(w);
                int ans = (it == counts.end() ? 0 : it->second);
                cout << ans << '\n';
                break;
            }
            case 3: {
                if (words.empty()) {
                    cout << 0 << '\n';
                    break;
                }
                int best = 0;
                auto it = words.lower_bound(w);
                if (it != words.end()) best = max(best, lcp(*it, w));
                if (it != words.begin()) {
                    auto itPrev = it;
                    --itPrev;
                    best = max(best, lcp(*itPrev, w));
                }
                cout << best << '\n';
                break;
            }
            default:
                break;
        }
    }
    return 0;
}