Pagini recente » Cod sursa (job #2931903) | Cod sursa (job #197575) | Cod sursa (job #2812651) | Cod sursa (job #627758) | Cod sursa (job #2305245)
#include <cstdio>
#include <cstring>
/// nod
struct Trie{
int ct,ct_son;
Trie *son[26];
Trie(){
ct=ct_son=0;
memset(son,0,sizeof(son));
}
};
Trie *root=new Trie;
void insert(Trie *nod,char *s){
if(*s==0){
++nod->ct;
return ;
}
if(nod->son[*s-'a']==0){
++nod->ct_son;
nod->son[*s-'a']=new Trie;
}
insert(nod->son[*s-'a'],s+1);
}
bool erase(Trie *nod,char *s){
if(*s==0)
--nod->ct;
else if(erase(nod->son[*s-'a'],s+1)){
--nod->ct_son;
nod->son[*s-'a']=0;
}
if(nod->ct==0&&nod->ct_son==0&&nod!=root){
delete nod;
return 1;
}
return 0;
}
int frequency(Trie *nod,char *s){
if(*s==0)
return nod->ct;
else{
if(nod->son[*s-'a']==0) return 0;
else return frequency(nod->son[*s-'a'],s+1);
}
}
int longest_common_prefix(Trie *nod,char *s){
if(*s==0||nod->son[*s-'a']==0)
return 0;
return 1+longest_common_prefix(nod->son[*s-'a'],s+1);
}
int tip;
char s[20];
int main(){
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
while(scanf("%d %s",&tip,s)!=EOF){
if(tip==0) insert(root,s);
else if(tip==1) erase(root,s);
else if(tip==2) printf("%d\n",frequency(root,s));
else printf("%d\n",longest_common_prefix(root,s));
}
return 0;
}