Cod sursa(job #3340433)

Utilizator Stefan_NicaStefan Nica Stefan_Nica Data 14 februarie 2026 11:28:42
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.94 kb
#include <bits/stdc++.h>
#define ull unsigned long long
#define ll long long
#define MOD 1000000007
#define NMAX 2e6

std::ifstream f("trie.in");
std::ofstream g("trie.out");

struct nod{
    std::unordered_map<char, int> fr;
    int ct = 0;
    int nr = 0;
};
std::vector<nod> v;

int c;
void add(std::string s, int indice, int nod1){
    if(indice == s.size()){
        v[nod1].ct ++; return;
    }
    if(!v[nod1].fr[s[indice]]){
        nod k;
        v.push_back(k);
        v[nod1].fr[s[indice]] = v.size() - 1;
    }
    v[v[nod1].fr[s[indice]]].nr ++;
    
    add(s, indice + 1, v[nod1].fr[s[indice]]);
}
void stergere(std::string s, int indice, int nod1){
    if(indice != s.size()){
        if(v[v[nod1].fr[s[indice]]].nr)
            --v[v[nod1].fr[s[indice]]].nr;
        stergere(s, indice + 1, v[nod1].fr[s[indice]]);
    }
    else --v[nod1].ct;
}
void check(std::string s, int indice, int nod1){
    if(indice == s.size())
        g << v[nod1].ct << '\n';
    else{
        if(!v[nod1].fr[s[indice]]){
            nod k;
            v.push_back(k);
            v[nod1].fr[s[indice]] = v.size() - 1;
        }
        check(s, indice + 1, v[nod1].fr[s[indice]]);
    }
}
void check1(std::string s, int indice, int nod1, int lg){
    if(indice == s.size() || !v[nod1].fr[s[indice]])
        g << lg << '\n';
    else{
        if(v[v[nod1].fr[s[indice]]].nr)
            check1(s, indice + 1, v[nod1].fr[s[indice]], lg + 1);
        else g << lg << '\n';
    }
}
int main(){
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(NULL);
    std::cout.tie(NULL);
    f.tie(NULL);
    g.tie(NULL);

    nod k;
    v.push_back(k);
    std::string s;
    while(f >> c >> s){
        if(c == 0) 
            add(s, 0, 0);
        if(c == 1)
            stergere(s, 0, 0);
        if(c == 2)
            check(s, 0, 0);
        if(c == 3)
            check1(s, 0, 0, 0);
    }
    
    return 0;
}