Pagini recente » Statistici Pacurar Cristian (Pacurar_Cristian) | Cod sursa (job #1796723) | Atasamentele paginii Alegerile | Cod sursa (job #636769) | Cod sursa (job #795506)
Cod sursa(job #795506)
#include <stdio.h>
#include <string.h>
#define LMAX 27
struct trie
{
int pass,end;
trie *fiu[LMAX];
trie()
{
pass=end=0;
memset(fiu,0,sizeof(fiu));
}
};
trie *T=new trie;
char A[LMAX];
void ins(trie *nod,char *x)
{
nod->pass++;
if (*x=='\n')
{
nod->end++;
return ;
}
if (nod->fiu[*x-'a']==0)
nod->fiu[*x-'a']=new trie;
ins(nod->fiu[*x-'a'],x+1);
}
int del(trie *nod,char *x)
{
nod->pass--;
if (*x=='\n')
nod->end--;
else
if (del(nod->fiu[*x-'a'],x+1))
nod->fiu[*x-'a']=0;
if (nod->pass==0 && nod!=T)
{
delete nod;
return 1;
}
return 0;
}
int cnt(trie *nod,char *x)
{
if (*x=='\n')
return nod->end;
if (nod->fiu[*x-'a']==0)
return 0;
return cnt(nod->fiu[*x-'a'],x+1);
}
int lcp(trie *nod,char *x,int nr)
{
if (*x=='\n' || nod->fiu[*x-'a']==0)
return nr;
return lcp(nod->fiu[*x-'a'],x+1,nr+1);
}
int main()
{
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
fgets(A+1,LMAX,stdin);
while (!feof(stdin))
{
switch (A[1])
{
case '0': ins(T,A+3); break ;
case '1': del(T,A+3); break ;
case '2': printf("%d\n",cnt(T,A+3)); break ;
case '3': printf("%d\n",lcp(T,A+3,0)); break ;
}
fgets(A+1,LMAX,stdin);
}
return 0;
}