Cod sursa(job #585400)

Utilizator BlaugranasEnal Gemaledin Blaugranas Data 29 aprilie 2011 10:03:50
Problema Trie Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#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;}