Cod sursa(job #3161355)

Utilizator DariusM17Murgoci Darius DariusM17 Data 26 octombrie 2023 18:28:10
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <bits/stdc++.h>
using namespace std;
#define FAST ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0) ;
#define ll long long
ifstream fin("trie.in") ;
ofstream fout("trie.out") ;
struct Trie
{
    int cnt=0,cnt2=0 ;
    Trie *next[26]= {} ;
    void insereaza(string &s,int pos=0)
    {
        cnt2++ ;
        if(pos==s.size())
        {
            cnt++ ;
            return ;
        }
        if(!next[s[pos]-'a']) next[s[pos]-'a']=new Trie ;
        next[s[pos]-'a']->insereaza(s,pos+1) ;
    }
    int numara(string &s,int pos=0)
    {
        if(pos==s.size()) return cnt ;
        return next[s[pos]-'a']->numara(s,pos+1) ;
    }
    void sterge (string &s,int pos=0)
    {
        cnt2-- ;
        if(pos==s.size())
        {
            cnt-- ;
            return ;
        }
        next[s[pos]-'a']->sterge(s,pos+1) ;
        if(next[s[pos]-'a']->cnt2<=0)
        {
            delete next[s[pos]-'a'] ;
            next[s[pos]-'a']=nullptr ;
        }
    }
    int lcp(string &s,int pos=0)
    {
        if(s.size()==pos||!next[s[pos]-'a']) return 0;
        return next[s[pos]-'a']->lcp(s,pos+1)+1 ;
    }
};
Trie arb ;
int op;
string s ;
int main()
{
    while(fin>>op>>s)
    {
        if(op==0) arb.insereaza(s) ;
        else if(op==1) arb.sterge(s) ;
        else if(op==2) fout<<arb.numara(s)<<'\n' ;
        else if(op==3) fout<<arb.lcp(s)<<'\n' ;
    }
    return 0;
}