Pagini recente » Monitorul de evaluare | Cod sursa (job #1519539) | Cod sursa (job #2242119) | Monitorul de evaluare | Cod sursa (job #1630219)
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
struct nod
{
int val,nr;
nod *adr[27];
nod()
{
val = 0;
nr = 0;
memset( adr, 0, sizeof( adr ) );
}
};
nod *arbore = new nod;
void adauga(nod *curent, char *s)
{
if(*s == 0)
{
curent->val++;
return;
}
if(curent->adr[*s - 'a']==NULL)
{
curent->adr[*s - 'a'] = new nod;
curent->nr++;
}
adauga(curent->adr[*s - 'a'],s+1);
}
int sterge(nod *curent, char *s,int &ok)
{
if(*s == 0)
{
curent->val--;
}
else if(sterge(curent->adr[*s - 'a'],s+1,ok))
{
curent->adr[*s - 'a'] =0;
curent->nr--;
}
if(curent!=arbore&&curent->val == 0 && curent->nr == 0)
{
delete curent;
return 1;
}
return 0;
}
void aparitii(nod *curent, char *s)
{
if(curent == 0)
{
printf("0\n");
return;
}
if(*s == 0)
{
printf("%d\n",curent->val);
return;
}
aparitii(curent->adr[*s - 'a'],s+1);
}
void prefix(nod *curent, char *s, int m)
{
m++;
if((*s)&&curent->adr[*s-'a'])
prefix(curent->adr[*s-'a'],s+1,m);
else
printf("%d\n",m-1);
}
int main()
{
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
char s[25];
int op;
while(scanf("%d",&op)>0)
{
int m = 0;
int ok=0;
scanf("%s",&s);
if(op==0)
adauga(arbore,s);
if(op==1)
sterge(arbore,s,ok);
if(op==2)
aparitii(arbore,s);
if(op==3)
prefix(arbore,s,m);
}
return 0;
}