Cod sursa(job #2381100)

Utilizator dan.ghitaDan Ghita dan.ghita Data 16 martie 2019 00:26:28
Problema Trie Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.25 kb
#include <bits/stdc++.h>
#include <unordered_map>

using namespace std;

ifstream f("trie.in");
ofstream g("trie.out");

class TrieNode
{
    vector<TrieNode*> children;
    int cnt = 0;

    bool hasChildren()
    {
        return count_if(children.begin(), children.end(), [](TrieNode* ptr) { return ptr != nullptr; }) > 0;
    }

public:
    TrieNode()
    {
        children.resize(26, nullptr);
    }

    void insert(string const& s, int index = 0)
    {
        if (index == s.size())
        {
            ++cnt;
            return;
        }

        if (children[s[index] - 'a'] == nullptr)
            children[s[index] - 'a'] = new TrieNode();

        children[s[index] - 'a']->insert(s, index + 1);
    }

    bool remove(string const& s, int index = 0)
    {
        if (index == s.size())
        {
            --cnt;
            return cnt <= 0 && !hasChildren();
        }

        if (children[s[index] - 'a'] != nullptr)
        {
            bool removeNext = children[s[index] - 'a']->remove(s, index + 1);
            if (removeNext)
                delete children[s[index] - 'a'],
                children[s[index] - 'a'] = nullptr;

            return cnt <= 0 && !hasChildren();
        }
    }

    int count(string const& s, int index = 0)
    {
        if (index == s.size())
            return cnt;

        if (children[s[index] - 'a'] != nullptr)
            return children[s[index] - 'a']->count(s, index + 1);
        else
            return 0;
    }

    int prefix(string const& s, int index = 0)
    {
        if (index == s.size())
            return s.size();

        if (children[s[index] - 'a'] != nullptr)
            return children[s[index] - 'a']->prefix(s, index + 1);
        else
            return index;
    }
};

int main()
{
    int op;
    string s;

    TrieNode trie;
    while (!f.eof() && f >> op >> s)
        switch (op)
        {
        case 0:
            trie.insert(s);
            break;
        case 1:
            trie.remove(s);
            break;
        case 2:
            g << trie.count(s) << '\n';
            break;
        case 3:
            g << trie.prefix(s) << '\n';
            break;
        }

    return 0;
}