Pagini recente » Cod sursa (job #414866) | Cod sursa (job #3198469)
#include <fstream>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct nod
{
int nri;
int nrf;
nod* childs[27]= {0};
nod()
{
nri=0;
nrf=0;
for(int i=0;i<=26;i++)
{
childs[i]=NULL;
}
}
};
struct trie
{
nod root;
void add(char* q,nod* act)
{
if(*q !=0)
{
if(act->childs[*q-'a']==NULL)
{
act->childs[*q-'a']=new nod;
act->nri++;
}
add(q+1,act->childs[*q-'a']);
}
else
act->nrf++;
}
int numar_ap(char *q,nod*act)
{
if(*q != 0)
{
if(act->childs[*q-'a']==NULL)
return 0;
return numar_ap(q+1,act->childs[*q-'a']);
}
return act->nrf;
}
int l_prefix(char *q,nod* act)
{
if(*q != 0)
{
if(act->childs[*q-'a']==NULL)
return 0;
return 1 +l_prefix(q+1,act->childs[*q-'a']);
}
return 0;
}
int sterge(nod* act ,char *q)
{
if(*q==0)
{
act->nrf--;
}
else if (act->childs[*q-'a']==NULL)
return 0;
else if (sterge(act->childs[*q-'a'],q+1))
{
act->childs[*q-'a']=0;
act->nri--;
}
if(act->nrf==0 && act->nri==0 && act!=&root)
{
delete act;
return 1;
}
return 0;
}
}a;
char s[50];
int main()
{
while(fin.getline(s,49))
{
char op = s[0];
char *p = s+2;
if(op=='0')
{
a.add(p,&a.root);
}
else if (op=='2')
{
fout<<a.numar_ap(p,&a.root)<<'\n';
}
else if (op=='3')
{
fout<<a.l_prefix(p,&a.root)<<'\n';
}
else
{
a.sterge(&a.root,p);
}
}
}