Cod sursa(job #3299474)

Utilizator sergioneUngureanu Sergiu sergione Data 6 iunie 2025 22:00:17
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.33 kb
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <memory>
#define fastio ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);

using namespace std;

class Trie {
private:
    struct TrieNode {
        unordered_map<char, unique_ptr<TrieNode>> child;
        int pass_count;
        int end_count;
        TrieNode() : pass_count(0), end_count(0) {}
    };

    unique_ptr<TrieNode> root;

public:
    Trie() : root(make_unique<TrieNode>()) {}

    void insert(const string &s) {
        TrieNode* curr = root.get();
        curr->pass_count++;
        for (char ch : s) {
            if (curr->child.find(ch) == curr->child.end()) {
                curr->child[ch] = make_unique<TrieNode>();
            }
            curr = curr->child[ch].get();
            curr->pass_count++;
        }
        curr->end_count++;
    }

    void remove(const string &s) {
        TrieNode* curr = root.get();
        curr->pass_count--;
        for (char ch : s) {
            curr = curr->child[ch].get();
            curr->pass_count--;
        }
        curr->end_count--;
    }

    int count(const string &s) {
        TrieNode* curr = root.get();
        for (char ch : s) {
            if (curr->child.find(ch) == curr->child.end()) {
                return 0;
            }
            curr = curr->child[ch].get();
        }
        return curr->end_count;
    }

    int lcp(const string &s) {
        TrieNode* curr = root.get();
        int len = 0;
        for (char ch : s) {
            if (curr->child.find(ch) == curr->child.end()) {
                break;
            }
            TrieNode* next = curr->child[ch].get();
            if (next->pass_count <= 0) {
                break;
            }
            len++;
            curr = next;
        }
        return len;
    }
};

int main() {
    fastio
    ifstream cin("trie.in");
    ofstream cout("trie.out");

    Trie trie;
    int op;
    string word;
    while (cin >> op >> word) {
        if (op == 0) {
            trie.insert(word);
        } else if (op == 1) {
            trie.remove(word);
        } else if (op == 2) {
            cout << trie.count(word) << '\n';
        } else if (op == 3) {
            cout << trie.lcp(word) << '\n';
        }
    }

    return 0;
}