Cod sursa(job #3348438)

Utilizator Tudor.1234Holota Tudor Matei Tudor.1234 Data 21 martie 2026 21:35:05
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.58 kb
#include "bits/stdc++.h"

struct Node{
    std :: unordered_map < char, Node* > children;
    int cnt_pref, isEnd;
    Node(){
        isEnd = cnt_pref = 0;
    }
};

struct Trie{
    Node* root;

    Trie(){
        root = new Node();
    }

    void Insert(std :: string word){
        Node* current = root;
        for(auto i : word){
            if(current -> children[i] == nullptr){
                current -> children[i] = new Node();
            }
            current = current -> children[i];
            current -> cnt_pref++;
        }
        current -> isEnd++;
    }

    bool Search(std :: string word){
        Node*  current = root;
        for(auto i : word){
            if(current -> children.count(i) == 0){
                return false;
            }
            current = current -> children[i];
        }
        return current -> isEnd > 0;
    }

    void Erase(std :: string word){
        if(!Search(word)){
            return;
        }
        Node* current = root;
        for(auto i : word){
            Node* next_node = current -> children[i];
            next_node -> cnt_pref--;

            if(next_node -> cnt_pref == 0){
                delete next_node;
                current -> children.erase(i);
                return;
            }
            current = next_node;
        }
        current -> isEnd--;
    }

    int Count(std :: string word){
        Node* current = root;
        for(char i : word){
            if(current -> children.count(i) == 0){
                return 0;
            }
            current = current -> children[i];
        }
        return current -> isEnd;
    }

    int LCP(std :: string word){
        Node* current = root;
        int len = 0;
        for(auto i : word){
            if(current -> children.count(i) == 0){
                break;
            }
            current = current -> children[i];
            len++;
        }
        return len;
    }

};

Trie trie;

void Solve(){
    std :: string s;
    int type;
    while(std :: cin >> type >> s){
        if(type == 0){
            trie.Insert(s);
        }
        if(type == 1){
            trie.Erase(s);
        }
        if(type == 2){
            std :: cout << trie.Count(s) << '\n';
        }
        if(type == 3){
            std :: cout << trie.LCP(s) << '\n';
        }
    }
}

signed main(){
    std :: ios_base :: sync_with_stdio(false);
    std :: cin.tie(nullptr);

    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);

    Solve();

    return 0;
}