Cod sursa(job #2381101)

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

using namespace std;

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

class TrieNode
{
    TrieNode* children[26];
    int cnt = 0, childrenCount = 0;

public:
    TrieNode()
    {
        for (int i = 0; i < 26; ++i)
            children[i] = 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(),
            ++childrenCount;

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

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

        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,
                --childrenCount;

            return cnt <= 0 && childrenCount <= 0;
        }
    }

    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;
}