Cod sursa(job #3308545)

Utilizator aaagabiTurbinca Gabriel aaagabi Data 25 august 2025 23:50:49
Problema Trie Scor 55
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.78 kb
#include <bits/stdc++.h>

//#pragma GCC target("avx2")
#define int long long
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//#pragma GCC optimize("O3")
//#pragma GCC optimize("Ofast")
//using namespace __gnu_pbds;
using namespace std;
//ofstream fout("date.out");
ifstream fin("trie.in");
ofstream fout("trie.out");
//template <class T>
//using Tree =
//    tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef long double ld;
int n;
int pi[4000005];
int op;
int tr(char x)
{
    return x-'a';
}
struct node
{
    char val;
    int cnt;
    int nrf;
    bool isleaf;
    node * next[26];
    node * fa;
    node()
    {
        for(int i=0;i<26;i++)
            next[i]=NULL;
        fa=NULL;
        cnt=0;
        isleaf =false;
        nrf=0;
    }
};
node * root=new node;
string s;
void insertst(string s)
{
    node *a=root;
    for(int i=0;i<s.size();i++)
    {
        char c=s[i];
        int x=tr(c);
        if(a->next[x]==NULL)
        {
            a->nrf++;
            a->next[x]=new node;
            a->next[x]->val=c;
            a->next[x]->fa=a;
        }
        a=a->next[x];
        if(i==s.size()-1)
            {
                a->isleaf=true;
                a->cnt++;
            }
    }
}
void delst(string s)
{
    node *a=root;
    for(int i=0;i<s.size();i++)
    {
        char c=s[i];
        int x=tr(c);
        a=a->next[x];
    }
    a->cnt--;
    int ln=s.size()-1;
    if(a->cnt==0)
    {
        a->isleaf=false;
        while(a->nrf==0&&a!=root)
        {
            node *x=a->fa;
            delete a;
            a=x;
            a->nrf--;
            a->next[tr(s[ln])]=NULL;
            ln--;
        }
    }
}
void printst(string s)
{
    node *a=root;
    for(int i=0;i<s.size();i++)
    {
        char c=s[i];
        int x=tr(c);
        if(a->next[x]==NULL)
        {
            fout<<"0\n";
            return;
        }
        a=a->next[x];
    }
    fout<<a->cnt<<'\n';
}
void printpref(string s)
{
    node *a=root;
    if(s[2]=='t')
        int ok=1;
    for(int i=0;i<s.size();i++)
    {
        char c=s[i];
        int x=tr(c);
        if(a->next[x]==NULL)
        {
            fout<<i<<'\n';
            return;
        }
        a=a->next[x];
    }
    fout<<s.size()<<'\n';
}
void solve()
{
    fin>>s;
    if(op==0)
        insertst(s);
    if(op==1)
        delst(s);
    if(op==2)
        printst(s);
    if(op==3)
        printpref(s);
}

signed main()
{
    cin.tie(0)->sync_with_stdio(0);
    int t=1;
    //fin>>t;
    //int op;
    while(fin>>op)
        solve();
    return 0;
}