Cod sursa(job #3278832)

Utilizator tryharderulbrebenel mihnea stefan tryharderul Data 20 februarie 2025 20:51:36
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.91 kb
#include <bits/stdc++.h>

using namespace std;

class Trie {
private:
    struct Node {
        int cnt = 0, ends = 0;
        Node *t[26];
        Node() {
            for(int i = 0; i < 26; i++) {
                t[i] = nullptr;
            }
        }
    } *root;  

public:

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

    void insert(const string &word) {
        Node *curr = root;
        for(char c : word) {
            if(curr->t[c - 'a'] == nullptr) {
                curr->t[c - 'a'] = new Node();
            }
            curr = curr->t[c - 'a'];
            curr->cnt++;
        }
        curr->ends++;
    }

    int search(const string &word) {
        Node *curr = root;
        for(char c : word) {
            if(curr->t[c - 'a'] == nullptr) {
                return 0;
            }
            curr = curr->t[c - 'a'];
        }
        return curr->ends;
    }

    void remove(const string &word) {
        Node *curr = root;
        for(char c : word) {
            curr = curr->t[c - 'a'];
            curr->cnt--;
        }
        curr->ends--;
    }

    int longestCommonPrefix(const string &word) {
        int cnt = 0;
        Node *curr = root;
        for(char c : word) {
            if(curr->t[c - 'a'] == nullptr || curr->t[c - 'a']->cnt == 0) { 
                return cnt; 
            }
            curr = curr->t[c - 'a'];
            cnt++;
        }
        return cnt;
    }
};

int main() {

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

    int type;
    string word;
    Trie tr;
    while (in >> type >> word) {
        if (type == 0) {
            tr.insert(word);
        } else if (type == 1){
            tr.remove(word);
        } else if (type == 2) {
            out << tr.search(word) << '\n';
        } else {
            out << tr.longestCommonPrefix(word) << '\n';
        }   
    }

    return 0;
}