Cod sursa(job #3299466)

Utilizator sergioneUngureanu Sergiu sergione Data 6 iunie 2025 20:09:29
Problema Trie Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.27 kb
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <string>
#include <vector>
#define fastio ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);

using namespace std;

class TrieNode {
public:
    unordered_map<char, TrieNode*> child;
    int pass_count;
    int end_count;
    TrieNode() : pass_count(0), end_count(0) {}
};

class Trie {
public:
    TrieNode* root;

    Trie() {
        root = new TrieNode();
    }

    void insert(string word) {
        TrieNode* curr = root;
        curr->pass_count++;
        for (char c : word) {
            if (curr->child.find(c) == curr->child.end()) {
                curr->child[c] = new TrieNode();
            }
            curr = curr->child[c];
            curr->pass_count++;
        }
        curr->end_count++;
    }

    void remove(string word) {
        TrieNode* curr = root;
        curr->pass_count--;
        for (char c : word) {
            curr = curr->child[c];
            curr->pass_count--;
        }
        curr->end_count--;
    }

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

    int longestCommonPrefix(string word) {
        TrieNode* curr = root;
        int len = 0;
        for (char c : word) {
            if (curr->child.find(c) == curr->child.end()) {
                break;
            }
            TrieNode* next = curr->child[c];
            if (next->pass_count <= 1) {
                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.longestCommonPrefix(word) << '\n';
        }
    }

    return 0;
}