Cod sursa(job #606174)

Utilizator BlaugranasEnal Gemaledin Blaugranas Data 3 august 2011 15:23:21
Problema Trie Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include<fstream.h>
#define cat(s) ((*s)-'a')
class trie
      {public:
           int c,n;
           trie *f[26];
      trie()
           {c=n=0;
           memset(f,0,sizeof(f));}
      void aw(trie*,char*);
      int dw(trie*,char*);
      int cw(trie*,char*);
      int cp(trie*,char*,int);};
trie *t=new trie();

void trie::aw(trie *s,char *l) 
{if(*l=='\0') 
        {++s->c;
        return;}
if(!s->f[cat(l)]) 
        s->f[cat(l)]=new trie(),++s->n;
s->aw(s->f[cat(l)],l+1);}
            
int trie::dw(trie *s,char *l) 
{if(*l=='\0') 
        --s->c;
else 
        if(s->dw(s->f[cat(l)],l+1)) 
               s->f[cat(l)]=0,--s->n;
if(!s->c&&!s->n&&s!=t) 
      {delete s;
      return 1;}
return 0;}
        
int trie::cw(trie *s,char *l) 
{if(*l=='\0') 
        return s->c;
if(s->f[cat(l)]) 
        return cw(s->f[cat(l)],l+1);
return 0;}

int trie::cp(trie *s,char *l,int k) 
{if(*l=='\0'||!s->f[cat(l)]) 
       return k;
return cp(s->f[cat(l)],l+1,k+1);}

int main()
{int p;
char l[32];
ifstream h("trie.in");
ofstream g("trie.out");
while(!h.eof()) 
     {h>>p>>l; 
     if(!p) 
            t->aw(t,l);
     else 
            if(p==1) 
                   t->dw(t,l);
            else 
                   if(p==2)
                           g<<t->cw(t,l)<<'\n';
                   else 
                           g<<t->cp(t,l,0)<<'\n';}
return 0;}