Pagini recente » Statistici Debora Deleanu (deboradeleanu) | Cod sursa (job #1473293)
#include <bits/stdc++.h>
using namespace std;
#define letter s[i]-'a'
const int alpha_size = 26;
int op;
string str;
class PrefixTree {
public :
vector <PrefixTree*> son;
PrefixTree *root;
int count_words;
int count_childs;
PrefixTree(){
count_words=0;
count_childs=0;
son.resize(alpha_size,NULL);
}
void pushWord(PrefixTree *node, int i, string s){
if (!isalpha(s[i])) {
++node->count_words;
return;
}
if (!node->son[letter]) {
node->son[letter]=new PrefixTree; // if there is not a son which starts with this letter
++node->count_childs;
}
pushWord(node->son[letter],i+1,s);
}
bool popWord(PrefixTree* node,int i,string s){
if (!isalpha(s[i])) {
--node->count_words; // end of the string
}
else {
if (node->popWord(node->son[letter],i+1,s)) {
--node->count_childs;
node->son[letter]=NULL;
}
}
if (node->count_childs == 0 && node->count_words == 0 && node != root) {
delete node;
return 1;
}
return 0;
}
int getNumberOfWords(PrefixTree* node,int i,string s){
if (!isalpha(s[i])) return node->count_words;
if (!node->son[letter]) return 0;
return getNumberOfWords(node->son[letter],i+1,s);
}
int getLengthOfPrefix (PrefixTree* node, int i, string s) {
if (!isalpha(s[i]) || !node->son[letter] ) return i; // return the length found until now
return getLengthOfPrefix(node->son[letter],i+1,s); // otherwise go to the child with the next character
}
} Trie;
int main() {
freopen ("trie.in","r",stdin);
freopen ("trie.out","w",stdout);
Trie.root = new PrefixTree;
while (cin>>op>>str) {
switch(op){
case 0 : Trie.pushWord(Trie.root,0,str); break;
case 1 : Trie.popWord(Trie.root,0,str); break;
case 2 : cout<<Trie.getNumberOfWords(Trie.root,0,str)<<'\n'; break;
default : cout<<Trie.getLengthOfPrefix(Trie.root,0,str)<<'\n'; break;
}
}
return 0;
}