Cod sursa(job #3274788)

Utilizator cris71Vlad Bogdan Cristian cris71 Data 8 februarie 2025 11:10:00
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.08 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
int const sigma=27;
int const smax=27;
struct Trie
{
    int cnt=0,leaves=0;
    Trie *next[sigma]={};
public:

    void insertTrie(string S, int pos=0)
    {
        leaves++;
        if(pos==S.size())///pune int
        {
            cnt++;
        }
        else{
            char ch=S[pos]-'a';
            if(next[ch]==nullptr)
            {
                next[ch]=new Trie;
            }
            next[ch]->insertTrie(S,pos+1);
        }
    }
    void deleteTrie(string S, int pos=0)
    {
        leaves--;
        if(pos==S.size())
        {
            cnt--;
        }
        else
        {
            char ch=S[pos]-'a';
            next[ch]->deleteTrie(S,pos+1);
            if(next[ch]->leaves==0)///pot sterge toata ramura adica
            {
                next[ch]=nullptr;
                delete next[ch];
            }
        }
    }
    int countTrie(string S, int pos=0)
    {
        if(pos==S.size())
        {
            return cnt;
        }
        else
        {
            char ch=S[pos]-'a';
            if(next[ch]==nullptr)
            {
                return 0;
            }
            return next[ch]->countTrie(S,pos+1);
        }
    }
    int lcpTrie(string S, int pos=0)
    {
        if(pos==S.size())
        {
            return 0;
        }
        else
        {
            char ch=S[pos]-'a';
            if(next[ch]==nullptr)
            {
                return 0;
            }
            return 1+next[ch]->lcpTrie(S,pos+1);
        }

    }

};
Trie trie;
int type;
string S;
int main()
{
    while(fin>>type>>S)
    {
        if(type==0)
        {
            trie.insertTrie(S);
        }
        else if(type==1)
        {
            trie.deleteTrie(S);
        }
        else if(type==2)
        {
            fout<<trie.countTrie(S)<<'\n';
        }
        else if(type==3)
        {
            fout<<trie.lcpTrie(S)<<'\n';
        }
    }
    return 0;
}