Cod sursa(job #2965043)

Utilizator sergioneUngureanu Sergiu sergione Data 14 ianuarie 2023 11:59:17
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <bits/stdc++.h>

using namespace std;

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

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

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