Cod sursa(job #3182076)

Utilizator alexandru_ioan.06Alexandru Ioan alexandru_ioan.06 Data 8 decembrie 2023 17:19:32
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <bits/stdc++.h>

using namespace std;

class Trie
{
    int cnt = 0;
    int lvs = 0;
    Trie *next[26] = {};
public:
    void Insert (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);
        }
    }
    void Erase (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 == 0)
            {
                delete next[str[pos] - 'a'];
                next[str[pos] - 'a'] = nullptr;
            }
        }
    }
    int Count (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 (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);
    }
}trie;

int main()
{
    int op;
    string str;
    ifstream fin ("trie.in");
    ofstream fout ("trie.out");
    while(fin >> op >> str)
    {
        if(op == 0)
            trie.Insert(str);
        else if(op == 1)
            trie.Erase(str);
        else if(op == 2)
            fout << trie.Count(str) << '\n';
        else
            fout << trie.LCP(str) << '\n';
    }
}