Cod sursa(job #3344865)

Utilizator robertcosacCosac Robert-Mihai robertcosac Data 6 martie 2026 10:30:55
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
struct trie
{
    int sum, fv;
    int v[26];
};
vector <trie> a;
char s[22];
int curr=0;
int l;
void add (int x, int idx)
{
    a[x].sum++;
    if (idx==l)
        a[x].fv++;
    else
    {
        if (a[x].v[s[idx]-'a']==0)
        {
            a[x].v[s[idx]-'a']=++curr;
            a.push_back ({0, 0, 0});
        }
        add (a[x].v[s[idx]-'a'], idx+1);
    }
}
void del (int x, int idx)
{
    a[x].sum--;
    if (idx==l)
        a[x].fv--;
    else
        del (a[x].v[s[idx]-'a'], idx+1);
}
int getfv (int nod, int idx)
{
    if (idx==l)
        return a[nod].fv;
    if (!a[nod].v[s[idx]-'a'])
        return 0;
    return getfv (a[nod].v[s[idx]-'a'], idx+1);

}
int pref (int nod, int idx)
{
    if (a[nod].sum==0)
        return max (idx-1, 0);
    if (idx==l)
        return idx;
    if (a[nod].v[s[idx]-'a']==0)
        return idx;
    return pref (a[nod].v[s[idx]-'a'], idx+1);
}
signed main ()
{
    int op;
    a.push_back({0, 0, 0});
    while (f>>op)
    {
        f >> (s);
        l=strlen (s);
        if (op==0)
            add (0, 0);
        if (op==1)
            del (0, 0);
        if (op==2)
            g << getfv (0, 0)<<'\n';
        if (op==3)
            g << pref (0, 0) << '\n';
    }
}