Cod sursa(job #3330244)

Utilizator coco11coraline kalbfleisch coco11 Data 18 decembrie 2025 10:15:32
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <bits/stdc++.h>
using namespace std;

#define int long long

struct Node {
    int cntEnd;
    int cntPass;
    array<Node*,26> nxt;
    Node(){ cntEnd=0; cntPass=0; nxt.fill(nullptr); }
};

struct Trie {
    Node* root;
    Trie(){ root=new Node(); }
    void add(const string &w){
        Node* cur=root;
        cur->cntPass++;
        for(char ch:w){
            int idx=ch-'a';
            if(!cur->nxt[idx]) cur->nxt[idx]=new Node();
            cur=cur->nxt[idx];
            cur->cntPass++;
        }
        cur->cntEnd++;
    }
    void del(const string &w){
        Node* cur=root;
        cur->cntPass--;
        for(char ch:w){
            int idx=ch-'a';
            cur=cur->nxt[idx];
            cur->cntPass--;
        }
        cur->cntEnd--;
    }
    int count(const string &w){
        Node* cur=root;
        for(char ch:w){
            int idx=ch-'a';
            if(!cur->nxt[idx]) return 0;
            cur=cur->nxt[idx];
        }
        return cur->cntEnd;
    }
    int longestPrefix(const string &w){
        Node* cur=root;
        int ans=0;
        for(char ch:w){
            int idx=ch-'a';
            if(!cur->nxt[idx]) break;
            cur=cur->nxt[idx];
            if(cur->cntPass>0) ans++;
            else break;
        }
        return ans;
    }
};

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);

    Trie T;
    string op,w;
    while(cin>>op){
        if(op=="0"){ cin>>w; T.add(w); }
        else if(op=="1"){ cin>>w; T.del(w); }
        else if(op=="2"){ cin>>w; cout<<T.count(w)<<"\n"; }
        else if(op=="3"){ cin>>w; cout<<T.longestPrefix(w)<<"\n"; }
    }
    return 0;
}