Cod sursa(job #3320558)

Utilizator and_Turcu Andrei and_ Data 6 noiembrie 2025 14:20:10
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.7 kb
#include <bits/stdc++.h>

using namespace std;


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

const int alphabet_size = 26;

class trie_node{
public:
    trie_node *next_letter[ alphabet_size ];
    int words_ending = 0;
    int ct_words = 0;

    trie_node()
    {
        for(int i = 0; i < alphabet_size; i++)
            next_letter[i] = NULL;
        words_ending = ct_words = 0;
    }
};

void add_word(std::string &word, int index, trie_node *current_node)
{
    current_node->ct_words += 1;
    
    if(index == word.size())
    {
        current_node->words_ending += 1;
        return;
    }

    int letter = word[index] - 'a';
// std::cout << char('a'+letter);
    if( current_node->next_letter[letter] == NULL ) 
    {
        trie_node *new_next_node = new trie_node;
        current_node->next_letter[letter] = new_next_node;
    }
    add_word(word, index + 1, current_node->next_letter[letter]);
}

void delete_word(std::string &word, int index, trie_node *current_node)
{
    current_node->ct_words -= 1;
    
    if(index == word.size())
    {
        current_node->words_ending -= 1;
        return;
    }

    int letter = word[index] - 'a';
// std::cout << char('a'+letter);
    delete_word(word, index + 1, current_node->next_letter[letter]);
    if( current_node->next_letter[letter]->ct_words == 0 )
    {
        delete current_node->next_letter[letter];
        current_node->next_letter[letter] = NULL;
    }
}

int count_word(std::string &word, int index, trie_node *current_node)
{
    if(index == word.size())
        return current_node->words_ending;
    
    int letter = word[index] - 'a';
    
    return count_word(word, index + 1, current_node->next_letter[letter]);
}

int longest_common_prefix_for_word(std::string &word, int index, trie_node *current_node)
{
    if( current_node == NULL or index == word.size())
        return 0;
    
    int letter = word[index] - 'a';
    
    if(current_node->next_letter[letter] != NULL)
        return 1 + longest_common_prefix_for_word(word, index + 1, current_node->next_letter[letter]);
    return 0;
}

trie_node *starting_node;

int main()
{
    starting_node = new trie_node;

    int operation;
    std::string s;

    while(fin >> operation)
    {
        fin >> s;
        if(operation == 0)
        {
// std::cout << "\n+";
            add_word(s, 0, starting_node);
        }
        if(operation == 1)
        {
// std::cout << "\n-";
            delete_word(s, 0, starting_node);
        }
        if(operation == 2)
        {
            fout << count_word(s, 0, starting_node) << "\n";
        }
        if(operation == 3)
        {
            fout << longest_common_prefix_for_word(s, 0, starting_node) << "\n";
        }
    }

    return 0;
}