Cod sursa(job #1399079)

Utilizator crucerucalinCalin-Cristian Cruceru crucerucalin Data 24 martie 2015 16:02:05
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.86 kb
#include <iostream>
#include <fstream>
#include <vector>


struct trie_node
{
    trie_node()
        : words(0)
        , children(26)
    {}

    int words;
    std::vector<trie_node> children;
};

void insertWord(trie_node &node, const std::string &word)
{
    if (!word.size())
        ++node.words;
    else
        insertWord(node.children[word.front() - 'a'], word.substr(1));
}

void deleteWord(trie_node &node, const std::string &word)
{
    if (!word.size())
        --node.words;
    else
        deleteWord(node.children[word.front() - 'a'], word.substr(1));
}

int getWordCount(trie_node &node, const std::string &word)
{
    if (!word.size())
        return node.words;
    if (node.children[word.front() - 'a'].children.size())
        return getWordCount(node.children[word.front() - 'a'], word.substr(1));
    return 0;
}

int getPreffixLen_impl(trie_node &node, const std::string &preffix, int level)
{
    if (!preffix.size() || !node.children[preffix.front() - 'a'].children.size())
        return level;

    return getPreffixLen_impl(node.children[preffix.front() - 'a'],
                              preffix.substr(1),
                              level + 1);
}

int getPreffixLen(trie_node &node, const std::string &preffix)
{
    return getPreffixLen_impl(node, preffix, 0);
}

int main()
{
    std::ios_base::sync_with_stdio(false);

    std::ifstream fin{"trie.in"};
    std::ofstream fout{"trie.out"};

    trie_node root;

    int op;
    std::string word;
    while (fin >> op >> word) {
        switch (op) {
            case 0:
                insertWord(root, word);
                break;
            case 1:
                deleteWord(root, word);
                break;
            case 2:
                fout << getWordCount(root, word);
                break;
            case 3:
                fout << getPreffixLen(root, word);
        }
    }

    return 0;
}