Pagini recente » Cod sursa (job #1788926) | Cod sursa (job #1462107) | Cod sursa (job #2125343) | Cod sursa (job #2923720) | Cod sursa (job #1488549)
#include <bits/stdc++.h>
using namespace std;
const int alpha_size = 26;
int op;
char word[30];
class PrefixTree {
public :
vector <PrefixTree*> son;
PrefixTree *root;
int count_words;
int count_childs;
//constructor
PrefixTree(){
this->count_words=0;
this->count_childs=0;
this->son.resize(alpha_size,NULL);
}
//public functions
void pushWord(PrefixTree *node, char *letter){
if (!isalpha(*letter)) {
++node->count_words;
return;
}
if (!node->son[*letter-'a']) {
node->son[*letter-'a']=new PrefixTree;
++node->count_childs;
}
pushWord(node->son[*letter-'a'],letter+1);
}
bool popWord(PrefixTree* node,char *letter){
if (!isalpha(*letter)) {
--node->count_words;
}
else {
if (node->popWord(node->son[*letter-'a'],letter+1)) {
--node->count_childs;
node->son[*letter-'a']=NULL;
}
}
if (node->count_childs == 0 && node->count_words == 0 && node != root) {
delete node;
return 1;
}
return 0;
}
int getNumberOfWords(PrefixTree* node,char *letter){
if (!isalpha(*letter)) return node->count_words;
if (!node->son[*letter-'a']) return 0;
return getNumberOfWords(node->son[*letter-'a'],letter+1);
}
int getLengthOfPrefix (PrefixTree* node, char *letter) {
if (!isalpha(*letter) || !node->son[*letter-'a'] ) return (letter-word);
return getLengthOfPrefix(node->son[*letter-'a'],letter+1);
}
} Trie;
int main() {
ifstream cin("trie.in");
ofstream cout("trie.out");
cin.tie();
Trie.root = new PrefixTree;
while (cin>>op>>word) {
switch(op){
case 0 : Trie.pushWord(Trie.root,word); break;
case 1 : Trie.popWord(Trie.root,word); break;
case 2 : cout<<Trie.getNumberOfWords(Trie.root,word)<<"\n"; break;
default : cout<<Trie.getLengthOfPrefix(Trie.root,word)<<"\n"; break;
}
}
return 0;
}