Cod sursa(job #606172)

Utilizator BlaugranasEnal Gemaledin Blaugranas Data 3 august 2011 15:15:22
Problema Trie Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include<stdio.h> 
typedef struct n
{char c;
int w,p;
struct n *e[26];}T;
char s[21];
int x,i;
 
T *init()
{T *t=new T;
t->w=t->p=0;
for(i=0;i<26;i++)
      t->e[i]=NULL;
return t;}
 
void aw(T *&t,char *s)
{if(*s=='\0')
      {t->w++;
      return;}
if(t->e[(*s)-'a']==NULL)
      t->e[(*s)-'a']=init(),t->p++;
aw(t->e[(*s)-'a'],s+1);}
 
int dw(T *&t,char *s,T *r)
{if((*s)=='\0')
      t->w--;
else 
      if(dw(t->e[(*s)-'a'],s+1,r)==1) 
             t->e[(*s)-'a']=NULL,t->p--;
if(!t->w&&!t->p&&t!=r) 
      {delete t;
      return 1;}
return 0;}
        
int cw(T *t,char *s) 
{if((*s)=='\0') 
       return t->w;
if(t->e[(*s)-'a']!=NULL) 
       return cw(t->e[(*s)-'a'],s+1);
return 0;}

int cp(T *t,char *s,int lg) 
{if((*s)=='\0'||t->e[(*s)-'a']==NULL) 
        return lg;
return cp(t->e[(*s)-'a'],s+1,lg+1);}

int main()
{freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
T *t=init(),*r;
while(!feof(stdin))
      {scanf("%d%s\n",&x,&s);
      if(!x)
              aw(t,s);
      else
              if(x==1)
                     r=init(),dw(t,s,r);
              else
                     if(x==2)
                             printf("%d\n",cw(t,s));
                     else
                             printf("%d\n",cp(t,s,0));}
return 0;}