Pagini recente » Cod sursa (job #211496) | Cod sursa (job #2932715) | Cod sursa (job #399315) | Cod sursa (job #357270)
Cod sursa(job #357270)
#include <cstdio>
#include <cstring>
struct node{
node* l[26];
int n;
};
node* root;
void add(char* w,int n){
node* tmp=root;
int i;
for(i=0;i<n;i++){
if(tmp->l[w[i]]==NULL){
node* t=new node;
t->n=0;
for(int j=0;j<26;j++)
t->l[j]=NULL;
tmp->l[w[i]]=t;
}
tmp=tmp->l[w[i]];
}
tmp->n++;
}
void remove(char* w,int n){
node* tmp=root;
int i;
for(i=0;i<n;i++)
tmp=tmp->l[w[i]];
tmp->n--;
if(tmp->n==0){
for(i=0;i<26;i++)
if(tmp->l[i])
break;
if(i==26){
tmp=root;
for(i=0;i<n-1;i++)
tmp=tmp->l[w[i]];
delete tmp->l[w[i]];
tmp->l[w[i]]=NULL;
}
}
}
int count(char* w,int n){
node* tmp=root;
int i;
for(i=0;i<n;i++)
if(tmp)
tmp=tmp->l[w[i]];
else
return 0;
return tmp->n;
}
int share(char* w,int n){
node* tmp=root;
int i,j,max=0;
for(i=0;i<n&&tmp;i++){
for(j=0;j<26;j++)
if(tmp->l[j])
break;
if(j<26||tmp->n)
max=i;
tmp=tmp->l[w[i]];
}
return max;
}
int main(){
freopen("trie.in","rt",stdin);
freopen("trie.out","wt",stdout);
int c,i,n;
char w[50],tmp[256],tmp2[256]="\n";
node* t=new node;
t->n=0;
for(int j=0;j<26;j++)
t->l[j]=NULL;
root=t;
while(!feof(stdin)){
fgets(tmp,256,stdin);
if(!strcmp(tmp,tmp2))
return 0;
strcpy(tmp2,tmp);
sscanf(tmp,"%d%s",&i,w);
n=strlen(w);
for(c=0;c<n;c++)
w[c]-='a';
switch(i){
case 0: add(w,n);break;
case 1: remove(w,n);break;
case 2: printf("%d\n",count(w,n));break;
case 3: printf("%d\n",share(w,n));break;
}
}
return 0;
}