Pagini recente » Cod sursa (job #220558) | Cod sursa (job #2238619) | Cod sursa (job #3241482) | Cod sursa (job #2761422) | Cod sursa (job #2482849)
#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) {
for (auto it : nw) {
if (node -> ch[it - 'a'] == NULL) { node -> ch[it - 'a'] = new Trie ; }
node = node -> ch[it - 'a'] ; node -> nrpref ++ ;
}
node -> nrcuv ++ ;
}
bool erase_from_trie(Trie *&node, std::string nw, int index) {
node -> nrpref -- ;
if (index == nw.size()) { node -> nrcuv -- ;
} 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) {
for (auto it : nw) {
node = node -> ch[it - 'a'] ;
}
return node -> nrcuv ;
}
int prefix(std::string nw, Trie *node) {
int i ;
for (i = (0) ; i < nw.size() ; ++ i) {
if (node -> ch[nw[i] - 'a'] == NULL) { break ; }
node = node -> ch[nw[i] - 'a'] ;
}
return i ;
}
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) ;
} else if (type == 1) {
erase_from_trie(root, ss, 0) ;
} else if (type == 2) {
ans = aparitii(ss, root) ;
std::cout << ans << '\n' ;
} else {
ans = prefix(ss, root) ;
std::cout << ans << '\n' ;
}
}
}