Cod sursa(job #748137)

Utilizator Anna_cristinaButucea Ana Cristina Anna_cristina Data 12 mai 2012 16:03:31
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
#include<fstream>
//#include<iostream.h>
//#include<conio.h>
#include<string.h>

using namespace std;

struct nod
{int nr_ap,sters;
 nod * cuv[27];
 nod()
   {for(int i=26; i--;)
       cuv[i]=0;
    nr_ap=0;
    sters=0;
   }
};

nod * r, * p;

void adauga(char s[21])
{int i,x;
 for(i=0;i<strlen(s);i++)
    {x=s[i]-'a';
     if(p->cuv[x]==NULL)
       {p->cuv[x]=new nod;
        p=p->cuv[x];
        p->nr_ap=0;
        }
        else
          p=p->cuv[x];
     }
 p->nr_ap++;     
 p->sters=1;
} 

void sterge(char s[21])
{int i,x;
 for(i=0;i<strlen(s);i++)
    {x=s[i]-'a';
     if(p->cuv[x]!=NULL)
        p=p->cuv[x];  
     }  
 p->nr_ap--;
 p->sters=-1;    
 }

int nr_aparitii(char s[21])
{int i,x;
 for(i=0;i<strlen(s);i++)
    {x=s[i]-'a';
     if(p->cuv[x]!=NULL)
        p=p->cuv[x];
      else  return 0;
     }
 return p->nr_ap;       
 }

int prefix(char s[21])
{int i,x,y,gasit=1,nr=0;
 nod * w;
 w=new nod;
 for(i=0;i<strlen(s) && gasit==1;i++)
    {x=s[i]-'a';
     if(i==(strlen(s)-1) && p->cuv[x]->nr_ap==1)
           return nr;
     if(p->cuv[x]!=NULL && p->cuv[x]->sters!=-1) 
         {p=p->cuv[x];
          nr++;
          }
         else  gasit=0;
     }   
 return nr;    
 }

int main()
{int i,x;
 char s[21];
 r=new nod;
 p=new nod;
 p=r;
   
 ifstream f("trie.in");
 ofstream g("trie.out");  
 while(f>>x>>s)
   {if(x==0)       {p=r;adauga(s);}
      else
       if(x==1)    {p=r;sterge(s);}
        else
         if(x==2)  {p=r;g<<nr_aparitii(s)<<"\n";}
          else     {p=r;g<<prefix(s)<<"\n";}
    } 
 f.close();
 g.close();     
 //getch();
 return 0;
}