Pagini recente » Cod sursa (job #1030234) | Cod sursa (job #1252005)
#include <cstdio>
using namespace std;
FILE*f=fopen("trie.in","r");
FILE*h=fopen("trie.out","w");
struct nod{
nod *fii[26];
int nrp,nrc;
nod(){
nrp=nrc=0;
for ( int i=0;i<26;++i )
fii[i]=NULL;
}
};
nod *r;
nod *adauga(nod *p,char *s){
if ( p==NULL ) p=new nod;
p->nrp++;
if ( s[0]==0 )
p->nrc++;
else
p->fii[s[0]-'a']=adauga(p->fii[s[0]-'a'],s+1);
return p;
}
nod *sterge(nod *p,char *s){
p->nrp--;
if ( s[0]==0 )
p->nrc--;
else
p->fii[s[0]-'a']=sterge(p->fii[s[0]-'a'],s+1);
if ( p->nrp==0 ){
delete p;
return NULL;
}
return p;
}
int apar(nod *p,char *s){
if (p == NULL)
return 0;
if ( s[0]==0 )
return p->nrc;
return apar(p->fii[s[0]-'a'],s+1);
}
int prefix(nod *p,char *s){
if ( p==NULL ) return -1;
if ( s[0]==0 ) return -2;
return 1+prefix(p->fii[s[0]-'a'],s+1);
}
char c[21];
int t;
int main(){
while ( fscanf(f,"%d %s\n",&t,&c)!=EOF ){
if ( t==0 )
r=adauga(r,c);
if ( t==1 )
r=sterge(r,c);
if ( t==2 )
fprintf(h,"%d\n",apar(r,c));
if ( t==3 )
fprintf(h,"%d\n",prefix(r,c));
}
return 0;
}