Cod sursa(job #3294772)

Utilizator EricDimiericdc EricDimi Data 28 aprilie 2025 09:42:23
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.92 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("trie.in");
ofstream g("trie.out");

const int SIGMA = 26;

class Trie {
private:
    int cnt = 0; // numarul de cuvinte care se termina in nodul curent
    int lvs = 0; // suma valorilor cnt din subarborele nodului curent
    Trie *next[SIGMA] = {};
public:
    void insert(const string& str, int pos = 0) {
        lvs++;
        if (pos == str.size())
            cnt++;
        else {
            if (!next[str[pos] - 'a'])
                next[str[pos] - 'a'] = new Trie;
            next[str[pos] - 'a']->insert(str, pos + 1);
        }
    }
    
    int count(const string& str, int pos = 0) {
        if (pos == 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 == str.size())
            return 0;
        if (!next[str[pos] - 'a'])
            return 0;
        return 1 + next[str[pos] - 'a']->lcp(str, pos + 1);
    }
    
    void erase(const string& str, int pos = 0) {
        lvs--;
        if (pos == 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 main() {
    Trie trie;
    int op;
    string str;
    
    while (f >> op >> str) {
        switch (op) {
        case 0: 
            trie.insert(str); 
            break;
        case 1:
            trie.erase(str);
            break;
        case 2:
            g << trie.count(str) << "\n";
            break;
        case 3:
            g << trie.lcp(str) << "\n";
            break;
        }
    }
    
    f.close();
    g.close();
    return 0;
}