Cod sursa(job #585404)

Utilizator BlaugranasEnal Gemaledin Blaugranas Data 29 aprilie 2011 10:09:50
Problema Trie Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include<fstream.h> 
typedef struct node
{char c;
int w,p;
struct node *edge[26];}Trie;
char s[30];
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()
{ifstream f("trie.in");
ofstream g("trie.out");
Trie *t=init();
for(;!f.eof();f.get())
      {f>>x;
      f>>s;
      if(f.good())
              if(x==0)
                      aw(t,s);
              else
                      if(x==1)
                              dw(t,s);
                      else
                              if(x==2)
                                      g<<cw(t,s)<<'\n';
                              else
                                      if(x==3)
                                               g<<cp(t,s,0)<<'\n';}
f.close();
g.close();
return 0;}