Cod sursa(job #2484039)

Utilizator rares404AlShaytan - Balasescu Rares rares404 Data 30 octombrie 2019 17:23:05
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.24 kb
#include <bits/stdc++.h>

struct Trie {
        Trie *ch[28] ;
        int nrcuv, nrpref ;
        Trie() {
                for (int i = 0 ; i <= 27 ; ++ i) { this -> ch[i] = NULL ; }
                this -> nrcuv = this -> nrpref = 0 ;
        }
};

Trie *root = new Trie ;
std::string nw ;

void add_in_trie (Trie *node, int index) {
        node -> nrpref ++ ;
        if (index == nw.size()) {
                node -> nrcuv ++ ;
                return ;
        }
        if (node -> ch[nw[index] - 'a'] == NULL) {
                node -> ch[nw[index] - 'a'] = new Trie ;
        }
        add_in_trie(node -> ch[nw[index] - 'a'], index + 1) ;
}

void erase_from_trie (Trie *&node, int index) {
        node -> nrpref -= 1 ;
        if (index == nw.size()) {
                node -> nrcuv -= 1 ;
        } else {
                erase_from_trie (node -> ch[nw[index] - 'a'], index + 1) ;
        }
        if (node != root && node -> nrpref == 0) {
                delete node, node = NULL ;
        }
}

int aparitii (Trie *node, int index) {
        if (index == nw.size()) {
                return node -> nrcuv ;
        }
        if (node -> ch[nw[index] - 'a'] == NULL) {
                return 0 ;
        }
        return aparitii (node -> ch[nw[index] - 'a'], index + 1) ;
}

int prefix (Trie *node, int index) {
        if (index == nw.size()) {
                return index ;
        }
        if (node -> ch[nw[index] - 'a'] == NULL) {
                return index ;
        }
        return prefix (node -> ch[nw[index] - 'a'], index + 1) ;
}

int main() {
        freopen ("trie.in", "r", stdin) ;
        freopen ("trie.out", "w", stdout) ;
        int type, ans ;
        std::cin.tie(0) ;
        while (std::cin >> type >> nw) {
                if (type == 0) {
                        add_in_trie (root, 0) ;
                } else if (type == 1) {
                        erase_from_trie (root, 0) ;
                } else if (type == 2) {
                        ans = aparitii (root, 0) ;
                        std::cout << ans << '\n' ;
                } else {
                        ans = prefix (root, 0) ;
                        std::cout << ans << '\n' ;
                }
        }
}