Cod sursa(job #2665642)

Utilizator filiptudose2007Tudose Filip filiptudose2007 Data 31 octombrie 2020 10:31:52
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.97 kb
#include <bits/stdc++.h>
using namespace std;
int x,n;
char s[10005];
struct Node
{
    int val=0;
    int active_sons=0;
    Node *Next[27];
    Node()
    {
        val=active_sons=0;
        for(int i=0; i<=26; ++i)
        {
            Next[i]=nullptr;
        }
    }
}*Trie=new Node;
void update(Node *tree,char *word,int upd_val,int ramase)
{
    if(ramase==0)
    {
        tree->val+=upd_val;
        return;
    }
    int now=(*word-'a');
    if(tree->Next[now]==nullptr)
    {
        tree->active_sons++;
        tree->Next[now]=new Node;
    }
    update((tree->Next[now]),word+1,upd_val,ramase-1);
    if(upd_val==-1)
    {
        Node *Son=tree->Next[now];
        if((Son->val)==0&&Son->active_sons==0)
        {
            delete(Son);
            tree->active_sons--;
            tree->Next[now]=nullptr;
        }
    }
}
int querycuvant(Node *tree,char *word,int ramase)
{
    if(ramase==0)
    {
        return tree->val;
    }
    int now=(*word-'a');
    if(tree->Next[now]==nullptr)
    {
        return 0;
    }
    return querycuvant(tree->Next[now],word+1,ramase-1);
}
int LCP(Node *tree, char *word,int curr_level, int ramase)
{
    if(ramase==0)
    {
        return curr_level;
    }
    int now=(*word-'a');
    if(tree->Next[now]==nullptr)
    {
        return curr_level;
    }
    return LCP(tree->Next[now],word+1,curr_level+1,ramase-1);
}
int main()
{
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    cin.sync_with_stdio(false);
    cin.tie(0);
    Trie->val=1;
    while(cin>>x>>s)
    {
        n=strlen(s);
        if(x==0)
        {
            update(Trie,s,1,n);
        }
        else
        if(x==1)
        {
            update(Trie,s,-1,n);
        }
        else
        if(x==2)
        {
            cout<<querycuvant(Trie,s,n)<<'\n';
        }
        else
        {
            cout<<LCP(Trie,s,0,n)<<'\n';
        }
    }
    return 0;
}