Cod sursa(job #1399143)

Utilizator crucerucalinCalin-Cristian Cruceru crucerucalin Data 24 martie 2015 16:28:07
Problema Trie Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.49 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <memory>


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

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

void insertWord(const std::unique_ptr<trie_node> &node, const std::string &word)
{
    if (!word.size()) {
        ++node->words;
        return;
    }

    if (!node->children[word.front() - 'a']) {
        node->children[word.front() - 'a'].reset(new trie_node);
        ++node->childrenCnt;
    }

    insertWord(node->children[word.front() - 'a'], word.substr(1));
}

int deleteWord(std::unique_ptr<trie_node> &root,
               std::unique_ptr<trie_node> &node,
               const std::string &word)
{
    if (!word.size())
        --node->words;
    else if (deleteWord(root, node->children[word.front() - 'a'], word.substr(1)))
        node->childrenCnt--;

    if (!node->childrenCnt && !node->words && node != root) {
        node.reset();
        return 1;
    }

    return 0;
}

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

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

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

int getPreffixLen(const std::unique_ptr<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"};

    std::unique_ptr<trie_node> root(new trie_node);

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

    return 0;
}