Cod sursa(job #3301840)

Utilizator Cristian_NegoitaCristian Negoita Cristian_Negoita Data 30 iunie 2025 13:41:39
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
const int SIGMA = 26;
struct Node
{
    int children_cnt, ending;
    Node *children[SIGMA];
    Node()
    {
        children_cnt = ending = 0;
        fill(children, children + SIGMA, nullptr);
    }
};
Node *root = new Node();

void adauga(const string &word, Node *node = root, int poz = 0)
{
    if(poz == word.size())
    {
        node->ending++;
        return;
    }
    if(node->children[word[poz] - 'a'] == nullptr)
    {
        node->children[word[poz] - 'a'] = new Node();
        node->children_cnt++;
    }
    adauga(word, node->children[word[poz] - 'a'], poz + 1);
}

bool sterge(const string &word, Node *node = root, int poz = 0)
{
    if(poz == word.size())
        node->ending--;
    else if(sterge(word, node->children[word[poz] - 'a'], poz + 1) == true)
    {
        node->children[word[poz] - 'a'] = nullptr;
        node->children_cnt--;
    }
    if(node != root && node->children_cnt == 0 && node->ending == 0)
    {
        delete node;
        return true;
    }
    return false;
}

int word_count(const string &word, Node *node = root, int poz = 0)
{
    if(poz == word.size())
        return node->ending;
    if(node->children[word[poz] - 'a'] != nullptr)
        return word_count(word, node->children[word[poz] - 'a'], poz + 1);
    return 0;
}

int longest_prefix(const string &word, Node *node = root, int poz = 0)
{
    if(poz == word.size() || node->children[word[poz] - 'a'] == nullptr)
        return poz;
    return longest_prefix(word, node->children[word[poz] - 'a'], poz + 1);
}

int main()
{
    int cer;
    string word;
    while(fin >> cer >> word)
    {
        if(cer == 0)
            adauga(word);
        else if(cer == 1)
            sterge(word);
        else if(cer == 2)
            fout << word_count(word) << "\n";
        else
            fout << longest_prefix(word) << "\n";
    }

    fin.close();
    fout.close();
    return 0;
}