Pagini recente » Cod sursa (job #2405346) | Cod sursa (job #468284) | Cod sursa (job #194592) | Cod sursa (job #523134) | Cod sursa (job #2484034)
#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 ;
void add_in_trie (std::string nw, 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(nw, node -> ch[nw[index] - 'a'], index + 1) ;
}
void erase_from_trie (Trie *&node, std::string nw, int index) {
node -> nrpref -= 1 ;
if (index == nw.size()) {
node -> nrcuv -= 1 ;
} else {
erase_from_trie (node -> ch[nw[index] - 'a'], nw, index + 1) ;
}
if (node != root && node -> nrpref == 0) {
delete node, node = NULL ;
}
}
int aparitii (std::string nw, Trie *node, int index) {
if (index == nw.size()) {
return node -> nrcuv ;
}
if (node -> ch[nw[index] - 'a'] == NULL) {
return 0 ;
}
return aparitii (nw, node -> ch[nw[index] - 'a'], index + 1) ;
}
int prefix (std::string nw, Trie *node, int index) {
if (index == nw.size()) {
return index ;
}
if (node -> ch[nw[index] - 'a'] == NULL) {
return index ;
}
return prefix (nw, node -> ch[nw[index] - 'a'], index + 1) ;
}
int main() {
freopen ("trie.in", "r", stdin) ;
freopen ("trie.out", "w", stdout) ;
int type, ans ;
std::string ss ;
while (std::cin >> type >> ss) {
if (type == 0) {
add_in_trie (ss, root, 0) ;
} else if (type == 1) {
erase_from_trie (root, ss, 0) ;
} else if (type == 2) {
ans = aparitii (ss, root, 0) ;
std::cout << ans << '\n' ;
} else {
ans = prefix (ss, root, 0) ;
std::cout << ans << '\n' ;
}
}
}