Pagini recente » Cod sursa (job #1292146) | Cod sursa (job #585400)
Cod sursa(job #585400)
#include<stdio.h>
typedef struct node
{char c;
int w,p;
struct node *edge[26];}Trie;
char s[21];
int x;
Trie *init()
{int i;
Trie *t=new Trie;
t->w=t->p=0;
for(i=0;i<26;i++)
t->edge[i]=NULL;
return t;}
void aw(Trie *&t,char *s)
{if(*s=='\0')
{t->w++;
return;}
if(t->edge[(*s)-'a']==NULL)
{t->edge[(*s)-'a']=init();
t->p++;}
aw(t->edge[(*s)-'a'],s+1);}
Trie *r=init();
int dw(Trie *&t,char *s)
{if((*s)=='\0')
t->w--;
else
if(dw(t->edge[(*s)-'a'],s+1)!=0)
{t->edge[(*s)-'a']=NULL;
t->p--;}
if(t->w==0&&t->p==0&&t!=r)
{delete t;
return 1;}
return 0;}
int cw(Trie *&t,char *s)
{if((*s)=='\0')
return t->w;
if(t->edge[(*s)-'a']!=NULL)
return cw(t->edge[(*s)-'a'],s+1);
return 0;}
int cp(Trie *&t,char *s,int lg)
{if((*s)=='\0'||t->edge[(*s)-'a']==NULL)
return lg;
return cp(t->edge[(*s)-'a'],s+1,lg+1);}
int main()
{freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
Trie *t=init(),*r=init();
while(!feof(stdin))
{scanf("%d%s\n",&x,&s);
if(x==0)
aw(t,s);
else
if(x==1)
dw(t,s);
else
if(x==2)
printf("%d\n",cw(t,s));
else
printf("%d\n",cp(t,s,0));}
fclose(stdin);
fclose(stdout);
return 0;}