Cod sursa(job #3281756)

Utilizator catalinmarincatalinmarin catalinmarin Data 3 martie 2025 16:05:04
Problema Trie Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.26 kb
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");

class TrieNode {
    private:
        TrieNode *edg[26];
        int wordsEnded;
        int subtreeSize;
    public:
        TrieNode() {
            memset(edg, 0, sizeof edg);
            wordsEnded = 0;
            subtreeSize = 0;
        }

        void add(const string &s, int depth = 0) {

            subtreeSize++;
            if (depth == s.size()) {
                wordsEnded++;
                return;
            }

            int nextLetterIndex = s[depth] - 'a';
            if (edg[nextLetterIndex] == NULL)
                edg[nextLetterIndex] = new TrieNode();
            edg[nextLetterIndex]->add(s, depth + 1);

        }

        void remove(const string &s, int depth = 0) {
            subtreeSize--;
            if (depth == s.size()) {
                wordsEnded--;
                return;
            }
            int nextLetterIndex = s[depth] - 'a';
            edg[nextLetterIndex]->remove(s, depth + 1);
        }

        int leastCommonAncestor(const string &s, int depth = 0) {
            if (subtreeSize == 0) {
                return depth - 1;
            }
            int nextLetterIndex = s[depth] - 'a';
            if (edg[nextLetterIndex] != nullptr) {
                return edg[nextLetterIndex]->leastCommonAncestor(s, depth + 1);
            }
            return depth;
        }

        int findWordsEnded (const string &s, int depth = 0) {
            if (depth == s.size()) {
                return wordsEnded;
            }
            int nextLetterIndex = s[depth] - 'a';
            if (edg[nextLetterIndex] != nullptr) {
                return edg[nextLetterIndex]->findWordsEnded(s, depth + 1);
            }
            return 0;
        }
};

int main() {

    int operatie;
    string word;

    TrieNode *root = new TrieNode();

    while (fin >> operatie >> word) {
        if (operatie == 0) {
            root->add(word);
        } else if (operatie == 1) {
            root->remove(word );
        } else if (operatie == 2) {
            fout << root->findWordsEnded(word ) << '\n';
        } else if (operatie == 3) {
            fout << root->leastCommonAncestor(word) << '\n';
        }
    }

    return 0;
}