Cod sursa(job #3123470)

Utilizator radustn92Radu Stancu radustn92 Data 23 aprilie 2023 21:21:15
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.05 kb
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
const int SIGMA = 'z' - 'a' + 1;

struct trieNode {
    vector<trieNode*> children;
    int pass, end;

    trieNode() {
        children.assign(SIGMA, nullptr);
        pass = end = 0;
    }
};
trieNode* root = new trieNode();

void insertTrie(trieNode* root, string& word, int idx) {
    root -> pass++;
    if (idx == word.size()) {
        root -> end++;
        return;
    }
    int child = word[idx] - 'a';
    if (root -> children[child] == nullptr) {
        root -> children[child] = new trieNode();
    }
    insertTrie(root -> children[child], word, idx + 1);
}

bool deleteTrie(trieNode* root, string& word, int idx) {
    root -> pass--;
    if (idx == word.size()) {
        root -> end--;
        if (root -> pass == 0) {
            delete root;
            return true;
        }
        return false;
    }
    int child = word[idx] - 'a';
    if (deleteTrie(root -> children[child], word, idx + 1)) {
        root -> children[child] = nullptr;
    }
    if (root -> pass == 0) {
        delete root;
        return true;
    }
    return false;
}

int countTrie(trieNode* root, string& word) {
    for (char ch : word) {
        root = root -> children[ch - 'a'];
        if (root == nullptr) {
            return 0;
        }
    }
    return root -> end;
}

int commonPrefixTrie(trieNode* root, string& word) {
    for (int idx = 0; idx < word.size(); idx++) {
        root = root -> children[word[idx] - 'a'];
        if (root == nullptr) {
            return idx;
        }
    }
    return word.size();
}


int main() {
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);

    int opType;
    string word;
    while (cin >> opType >> word) {
        if (opType == 0) {
            insertTrie(root, word, 0);
        } else if (opType == 1) {
            deleteTrie(root, word, 0);
        } else if (opType == 2) {
            cout << countTrie(root, word) << "\n";
        } else {
            cout << commonPrefixTrie(root, word) << "\n";
        }
    }
    return 0;
}