Cod sursa(job #3274683)

Utilizator BuruianaRaresAndreiBuruiana Rares Andrei BuruianaRaresAndrei Data 8 februarie 2025 09:58:06
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <bits/stdc++.h>

using namespace std;

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

class Trie {
private:
    int cnt = 0;
    int lvs = 0;
    Trie *nxt[26] = {};
public:
    void insert(const string &str, int pos = 0) {
        lvs++;
        if(pos == str.size()) {
            cnt++;
        }
        else {
            if(!nxt[str[pos] - 'a']) {
                nxt[str[pos] - 'a'] = new Trie;
            }
            nxt[str[pos] - 'a']->insert(str, pos + 1);
        }
    }

    int count(const string &str, int pos = 0) {
        if(pos == str.size()) {
            return cnt;
        }
        if(!nxt[str[pos] - 'a']) {
            return 0;
        }
        return nxt[str[pos] - 'a']->count(str, pos + 1);
    }

    int lcp(const string &str, int pos = 0) {
        if(pos == str.size()) {
            return 0;
        }
        if(!nxt[str[pos] - 'a']) {
            return 0;
        }
        return 1 + nxt[str[pos] - 'a']->lcp(str, pos + 1);
    }

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

};

Trie t;

int main() {
    int tip; string s;
    while(in >> tip >> s) {
        if(tip == 0) {
            t.insert(s);
        }
        if(tip == 1) {
            t.erase(s);
        }
        if(tip == 2) {
            out << t.count(s) << '\n';
        }
        if(tip == 3) {
            out << t.lcp(s) << '\n';
        }
    }
    return 0;
}