Pagini recente » Cod sursa (job #1657021) | Cod sursa (job #275343) | Cod sursa (job #1595306) | Cod sursa (job #1650972) | Cod sursa (job #2433993)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
typedef string::iterator string_it;
struct trie{
int nr;
short nrchild;
trie *child[27];
trie(){
nr=nrchild=0;
memset(child,0,sizeof(child));
}
};
trie* T = new trie;
int lg;
string s;
string_it it;
void Add(trie*);
void Del(trie*);
int Cnt(trie*);
void Lg(trie*);
int main(){
short task;
while(fin>>task>>s){
it=s.begin();
switch(task){
case 0:
Add(T);
break;
case 1:
Del(T);
break;
case 2:
fout<<Cnt(T)<<'\n';
break;
case 3:
lg=0;
Lg(T);
fout<<lg<<'\n';
break;
}
}
return 0;
}
void Lg(trie* t){
char ch=*it-'a';
if(it==s.end() || t->child[ch] == false)
return;
++lg;
++it;
Lg(t->child[ch]);
}
int Cnt(trie* t){
char ch=*it-'a';
if(it==s.end())
return t->nr;
if(t->child[ch] == false)
return 0;
++it;
return Cnt(t->child[ch]);
}
void Del(trie* t){
if(it==s.end()){
--t->nr;
return;
}
char ch=*it-'a';
++it;
Del(t->child[ch]);
if(t->child[ch]->nrchild == 0 && t->child[ch]->nr == 0){
--(t->nrchild);
delete t->child[ch];
t->child[ch]=0; ///Why?
}
}
void Add(trie* t){
if(it==s.end()){
++t->nr;
return;
}
char ch=*it-'a';
// if(t->child[ch] && t->child[ch]->nrchild == 0 && t->child[ch]->nr == 0){
// delete t->child[ch];
// }
if(t->child[ch] == false){
t->child[ch]= new trie();
++t->nrchild;
}
++it;
Add(t->child[ch]);
}