Pagini recente » Borderou de evaluare (job #2119909) | Cod sursa (job #2727118)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("trie.in");
ofstream fout("trie.out");
int op;
char str[300];
struct Trie
{
Trie *f[28];
int nf,cnt;
Trie()
{
nf=cnt=0;
memset(f,0,sizeof(f));
}
};
Trie *T=new Trie;
inline void adauga(char ch[])
{
Trie *t=T;
char *p=ch;
while(*p!=0)
{
if(t->f[*p-'a']==0)
{
t->f[*p-'a']=new Trie;
t->nf++;
}
t=t->f[*p-'a'];
p++;
}
t->cnt++;
}
inline int sterge(char *p,Trie *t)
{
if(*p==0)
t->cnt--;
else if(sterge(p+1,t->f[*p-'a'])!=0)
{
t->f[*p-'a']=0;
t->nf--;
}
if(t->cnt==0 && t->nf==0 && t!=T)
{
delete t;
return 1;
}
return 0;
}
inline void aparitii(char ch[])
{
Trie *t=T;
char *p=ch;
while(*p!=0)
{
if(t->f[*p-'a']==0)
{
fout<<0<<'\n';
return;
}
t=t->f[*p-'a'];
p++;
}
fout<<(t->cnt)<<'\n';
}
inline void prefix(char ch[])
{
Trie *t=T;
char *p=ch;
int k=0;
while(*p!=0)
{
if(t->f[*p-'a']==0)
break;
t=t->f[*p-'a'];
p++;
k++;
}
fout<<k<<'\n';
}
int main()
{
while(fin>>op>>str)
{
if(op==0)
adauga(str);
if(op==1)
{
char *p=str;
sterge(p,T);
}
if(op==2)
aparitii(str);
if(op==3)
prefix(str);
}
return 0;
}