Pagini recente » Cod sursa (job #2240041) | Cod sursa (job #666898) | Cod sursa (job #1072483) | Cod sursa (job #2262885) | Cod sursa (job #2484039)
#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' ;
}
}
}