Cod sursa(job #2847034)

Utilizator GeorgeAndreiGeorge Andrei Iarca GeorgeAndrei Data 10 februarie 2022 01:40:37
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.14 kb
#include<iostream>
#include<cstring>
#include<fstream>

using namespace std;

const int SIGMA = 26;

struct TrieNode {
    int cnt; 
    int leaf; 
    TrieNode* next[SIGMA];
    bool isLeaf;

    TrieNode() : cnt(0), leaf(0), isLeaf(false) {
        memset(next, 0, sizeof(next));
    }
};

void insert(const string& word, int pos, TrieNode* node) {
    node->cnt ++;

    if (pos == word.size()) {
        node->leaf++;
        node->isLeaf = true;
        return;
    }

    int nextChar = word[pos] - 'a'; 
    
    if (!node->next[nextChar])
        node->next[nextChar] = new TrieNode();

    insert(word, pos+1, node->next[nextChar]);
}

void erase(const string& word, int pos, TrieNode*& node) {
    node->cnt --;
    if (pos == word.size()) {
        node->leaf --;
        return;
    }

    int nextChar = word[pos] - 'a';

    erase(word, pos + 1, node->next[nextChar]);
    if (node->next[nextChar]->cnt == 0) {
        delete node->next[nextChar];
        node->next[nextChar] = nullptr;
    }
        
}

int printCount(const string& word, int pos, TrieNode*& node) {
    if (pos == word.size())
        return node->leaf;
    
    int nextChar = word[pos] - 'a';
    
    if (node->next[nextChar] != nullptr) {
        return printCount(word, pos + 1, node->next[nextChar]);
    }
    
    return 0;
}

int longComPref(const string& word, int pos, const TrieNode* node) {
    
    if (node == nullptr or word.size() == pos)
        return (pos - (node == nullptr));

    int nextChar = word[pos] - 'a';
    
    return longComPref(word, pos + 1, node->next[nextChar]);

}

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

    int type;
    string word;

    TrieNode* root = new TrieNode();

    while (cin >> type >> word) {
        switch(type) {
            case 0:
                insert(word, 0, root);
                break;
            case 1:
                erase(word, 0, root);
                break;
            case 2:
                cout << printCount(word, 0, root) << "\n";
                break;
            case 3:
                cout << longComPref(word, 0, root) << "\n";
                break;
        }    
    }

    return 0;
}