Pagini recente » Cod sursa (job #2681107) | Cod sursa (job #2197695) | Cod sursa (job #2903557) | Cod sursa (job #2499710) | Cod sursa (job #3033067)
#include <fstream>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct nod
{
int nri;
int nrf;
nod* childs[30]= {0};
nod()
{
nri=0;
nrf=0;
for(int i=0;i<=29;i++)
{
childs[i]=0;
}
}
};
struct trie
{
nod root;
void add(char* q)
{
int p=0;
nod* act = &root;
while(q[p]!=0)
{
if(act->childs[q[p]-'a']==NULL)
{
act->childs[q[p]-'a']=new nod;
act->nri++;
}
act=act->childs[q[p]-'a'];
p++;
if(q[p]=='\0')
{
act->nrf++;
}
}
}
int numar_ap(char *q)
{
int p=0;
nod* act = &root;
while(q[p]!=0)
{
if(act->childs[q[p]-'a']==NULL)
{
return 0;
}
act=act->childs[q[p]-'a'];
p++;
if(q[p]=='\0')
{
return act->nrf;
}
}
}
int l_prefix(char *q)
{
int l=0;
int p=0;
nod* act = &root;
while(q[p]!=0)
{
if(act->childs[q[p]-'a']==NULL)
{
return l;
}
act=act->childs[q[p]-'a'];
p++;
if(q[p]=='\0')
{
return l;
}
l++;
}
}
int sterge(nod* act ,char *q)
{
if(*q==0)
{
act->nrf--;
}
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);
}
else if (op=='2')
{
fout<<a.numar_ap(p)<<'\n';
}
else if (op=='3')
{
fout<<a.l_prefix(p)<<'\n';
}
else
{
a.sterge(&a.root,p);
}
}
}