Cod sursa(job #3351733)

Utilizator vladneaguVladneagu vladneagu Data 21 aprilie 2026 10:21:31
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.95 kb
#include <bits/stdc++.h>
using namespace std;
struct Node{
    int endd,pref;
    vector<int> next;
    Node(){
        endd=0;
        pref=0;
        next.assign(26,-1);
    }
};
struct Trie{
    vector<Node> t;
    Trie(){
        t.push_back(Node());
    }
    void insertt(string s){
        int u=0;
        t[u].pref++;
        for(auto chh:s){
            int ch=chh-'a';
            if(t[u].next[ch]==-1){
                t[u].next[ch]=t.size();
                t.push_back(Node());
            }
            u=t[u].next[ch];
            t[u].pref++;
        }
        t[u].endd++;
    }
    int findexact(string s){
        int u=0;
        for(auto chh:s){
            int ch=chh-'a';
            if(t[u].pref==0 || t[u].next[ch]==-1)return 0;
            u=t[u].next[ch];
        }
        return t[u].endd;
    }
    int findpref(string s){
        int u=0;
        int cnt=0;
        //cout<<s<<endl;
        for(auto chh:s){
            int ch=chh-'a';
            //cout<<cnt<<" "<<ch<<" "<<t[u].pref<<endl;
            if(t[u].next[ch]==-1 || t[t[u].next[ch]].pref==0)return cnt;
            cnt++;
            u=t[u].next[ch];
        }
        return s.size();
    }
    void erasee(string s){
        //cout<<s<<endl;
        if(findexact(s)==0)return;
        int u=0;
        t[u].pref-=1;
        for(auto chh:s){
            int ch=chh-'a';
            u=t[u].next[ch];
            t[u].pref-=1;
            //cout<<ch<<" "<<t[u].pref<<endl;
        }
        t[u].endd-=1;
    }
};
signed main()
{
    ifstream cin("trie.in");
    ofstream cout("trie.out");
    Trie trie;
    int c;
    string s;
    while(cin>>c>>s){
        if(c==0){
            trie.insertt(s);
        }else if(c==1){
            trie.erasee(s);
        }else if(c==2){
            cout<<trie.findexact(s)<<"\n";
        }else if(c==3){
            cout<<trie.findpref(s)<<"\n";
        }
    }
    return 0;
}