Cod sursa(job #3306329)

Utilizator DragosVNVisanescu Dragos Nicholas DragosVN Data 9 august 2025 17:57:26
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.78 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("trie.in");
ofstream fout("trie.out");

class Trie{

    private:

    struct node{
    int wec = 0;    //word end count - how many times has the word that ends here appeared
    unordered_map<char,node*>um;    //map for descendents
    };
    node * root;

    void add_count( node* current,string w,int idx)
    {
        if(idx == w.size() )
        {
            current->wec ++;
        }
        else
        {
            if(current->um.find(w[idx] ) == current->um.end())
                current->um[w[idx] ] = new node;

            add_count(current->um[w[idx] ],w,idx+1);
        }
    }

    bool delete_count(node* current, string& w, int idx) {
    if (idx == w.size()) {
        if (current->wec > 0)
            current->wec--;
        // Check if node is now useless
        return current->wec == 0 && current->um.empty();
    }

    char ch = w[idx];
    auto it = current->um.find(ch);
    if (it != current->um.end()) {
        node* child = it->second;
        bool should_delete_child = delete_count(child, w, idx + 1);

        if (should_delete_child) {
            delete child;
            current->um.erase(ch);
        }
    }

    // After potential deletion of child, check if current node is now useless
    return current->wec == 0 && current->um.empty();
}
    int word_count( node* current,string w,int idx)
    {
        if(idx == w.size() )
        {
           return current -> wec;
        }
        else if(current->um.find(w[idx] ) != current->um.end())
            return word_count(current->um[w[idx] ],w,idx+1);
        else
            return 0;

    }
    int maxpl( node* current,string w,int idx,int lmax)
    {
        if(idx == w.size() || current->um.find(w[idx] ) == current->um.end())
        {
           return idx ;
        }
        return maxpl(current->um[w[idx]],w,idx+1,lmax);


    }
    public:

    Trie()
    {
        root = new node;
    }
    void add(string word)
    {
            add_count(root,word,0);
    }
    void Delete(string word)
    {
        delete_count(root,word,0);
    }
    int Count(string word)
    {
        return word_count(root,word,0);
    }
    int longest_prefix(string word)
    {
        return maxpl(root,word,0,0);
    }
};

int main()
{

    Trie trie;
    int op;
    string word;

    while(fin >> op >> word)
    {
        if(op==0)
        {
            trie.add(word);
        }
        else if(op==1)
        {
            trie.Delete(word);
        }
        else if(op==2)
        {
            fout << trie.Count(word) << '\n';
        }
        else
        {
            fout <<trie.longest_prefix(word) << '\n';
        }
    }
    return 0;
}