Cod sursa(job #3332055)

Utilizator GliggyGligor Andrei Gliggy Data 3 ianuarie 2026 16:08:02
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
// Copilot Rules:
// RULE: There shouldnt be any spaces in the code, except after commas.
// RULE: All variables in main should be declared globally, and can be used before they are defined.
// RULE: All open curly braces should be placed on the same line as the function or control structure they belong to, not on the line after.
#include <bits/stdc++.h>

using namespace std;
ifstream fin("trie.in");   //strudel
ofstream fout("trie.out"); //
struct nod{
    int cnt=0;
    nod *kid[30]={nullptr};
};
nod r;
string s;
void add(string a){
    nod *curr=&r;
    for(auto i:a){
        int lit=i-'a';
        if(curr->kid[lit]) curr=curr->kid[lit];
        else curr->kid[lit]=new nod, curr=curr->kid[lit];
    }
    curr->cnt++;
}
bool clean(nod *x){
    for(int i=0;i<26;i++) if(x->kid[i]!=nullptr) return 0;
    return 1;
}
bool nest(nod *x, int i){
    int lit=s[i]-'a';
    if(i<s.length()){
        if(nest(x->kid[lit], i+1)==1)
            x->kid[lit]=nullptr;
    }
    else x->cnt--;
    if(x->cnt==0&&clean(x)==1){
        delete x;
        return 1;
    }
    return 0;
}
void remove(){
    nod *curr=&r;
    nest(&r, 2);
}
int afis(string a){
    nod *curr=&r;
    for(auto i:a){
        int lit=i-'a';
        if(curr->kid[lit]) curr=curr->kid[lit];
        else return 0;
    }
    return curr->cnt;
}
int lgst(string a){
    int cnt=0;
    nod *curr=&r;
    for(auto i:a){
        int lit=i-'a';
        if(curr->kid[lit]) cnt++,curr=curr->kid[lit];
        else return cnt;
    }
    return cnt;
}
int main()
{
    while(getline(fin,s)){
        switch(s[0]){
            case '0':{ add(s.substr(2)); break;}
            case '1':{ remove(); break;}
            case '2':{ fout<<afis(s.substr(2))<<'\n'; break;}
            case '3':{ fout<<lgst(s.substr(2))<<'\n'; break;}
        }
    }
    return 0;
}