Cod sursa(job #3281280)

Utilizator darian4444Verniceanu Darian darian4444 Data 28 februarie 2025 21:19:42
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <bits/stdc++.h>

using namespace std;

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

int x;
string str;

struct Trie {
    int cnt = 0,lvs = 0;
    Trie *next[26] = {};

    void insert(const string &str, int pos = 0) {
        lvs++;
        if (pos == int(str.size()))
            cnt++;
        else {
            if (!next[str[pos] - 'a'])
                next[str[pos] - 'a'] = new Trie;
            next[str[pos] - 'a']->insert(str, pos+1);
        }
    }
    void erase(const string &str, int pos = 0) {
        lvs--;
        if (pos == int(str.size()))
            cnt--;
        else {
            next[str[pos] - 'a']->erase(str, pos+1);
            if (!next[str[pos] - 'a']->lvs){
                delete next[str[pos] - 'a'];
                next[str[pos] - 'a'] = nullptr;
            }
        }
    }
    int count(const string &str, int pos = 0) {
        if (pos == int(str.size()))
            return cnt;
        if (!next[str[pos] - 'a'])
            return 0;
        return next[str[pos] - 'a']->count(str, pos+1);
    }
    int lcp(const string &str, int pos = 0) {
        if (pos == int(str.size()))
            return pos;
        if (!next[str[pos] - 'a'])
            return pos;
        return next[str[pos] - 'a']->lcp(str, pos+1);
    }
};

Trie root;

int main() {
    while (fin >> x >> str){
        if (x == 0)
            root.insert(str);
        else if (x == 1)
            root.erase(str);
        else if (x == 2)
            fout << root.count(str) << "\n";
        else
            fout << root.lcp(str) << "\n";
    }
}