Cod sursa(job #3201841)

Utilizator sebuxSebastian sebux Data 9 februarie 2024 20:32:35
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.16 kb
#include <bits/stdc++.h>
std::ifstream fin("trie.in");
std::ofstream fout("trie.out");

#define SIZE 26
struct TrieNode
{
    TrieNode *childrens[SIZE];
    int nr_of_letters = 0;
    int nr_of_word = 0;
};
TrieNode *create_trie_node()
{
    TrieNode *node = new TrieNode;
    for (size_t i = 0; i < SIZE; ++i)
        node->childrens[i] = nullptr;
    return node;
}
void insert(TrieNode *root, std::string word)
{
    TrieNode *copy_root = root;
    for (char c : word)
    {
        int index = c - 'a';
        if (!copy_root->childrens[index])
            copy_root->childrens[index] = create_trie_node();
        copy_root->childrens[index]->nr_of_letters++;
        copy_root = copy_root->childrens[index];
    }
    copy_root->nr_of_word++;
}

void erase(TrieNode *root, std::string word)
{
    TrieNode *copy_root = root;
    for (char c : word)
    {
        int index = c - 'a';
        copy_root->childrens[index]->nr_of_letters--;
        copy_root = copy_root->childrens[index];
    }
    copy_root->nr_of_word--;
}
int search(TrieNode *root, std::string word)
{
    TrieNode *copy_root = root;
    for (char c : word)
    {
        int index = c - 'a';
        if (!copy_root->childrens[index])
            return 0;
        copy_root = copy_root->childrens[index];
    }
    return copy_root->nr_of_word;
}
int search_prefix(TrieNode *root, std::string word)
{
    TrieNode *copy_root = root;
    int cnt = 0;
    for (size_t i = 0; i < word.length(); ++i)
    {
        int index = word[i] - 'a';

        if (!copy_root->childrens[index])
            return cnt;

        if (copy_root->childrens[index]->nr_of_letters > 0)
            cnt = i + 1;

        copy_root = copy_root->childrens[index];
    }
    return cnt;
}

TrieNode *root = create_trie_node();
int main()
{
    int x;
    std::string s;
    while (fin >> x >> s)
    {
        switch (x)
        {
        case 0:
            insert(root, s);
            break;
        case 1:
            erase(root, s);
            break;
        case 2:
            fout << search(root, s) << "\n";
            break;
        case 3:
            fout << search_prefix(root, s) << "\n";
            break;
        }
    }

    return 0;
}