Pagini recente » Cod sursa (job #3176600) | Cod sursa (job #394112) | Cod sursa (job #2627909) | Cod sursa (job #3146448) | Cod sursa (job #228455)
Cod sursa(job #228455)
#include <cstdio>
typedef struct nod
{
int nrfii, nrcuv;
nod *fiu[30];
} *Trie;
Trie T = new nod;
void insert(Trie &A, char *s)
{
if(*s == '\n')
{
A -> nrcuv++;
return;
}
if(A -> fiu[*s -'a'] == NULL)
{
A -> nrfii++;
A -> fiu[*s - 'a'] = new nod;
}
insert(A -> fiu[*s - 'a'], s+1);
}
int del(Trie &A, char *s)
{
if(*s == '\n')
A -> nrcuv--;
else if(del(A -> fiu[*s - 'a'], s+1))
{
A -> fiu[*s - 'a'] = 0;
A -> nrfii--;
}
if(A -> nrfii == 0 && A -> nrcuv == 0 && A != T)
{
delete A;
return 1;
}
return 0;
}
int app(Trie A, char *s)
{
if(*s == '\n')
return A -> nrcuv;
return app(A -> fiu[*s - 'a'], s+1);
}
int pre(Trie A, char *s)
{
if((*s == '\n') || (A -> fiu[*s - 'a'] == NULL))
return 0;
return pre(A -> fiu[*s - 'a'], s+1) + 1;
}
int main()
{
freopen("trie.in","rt",stdin);
freopen("trie.out","wt",stdout);
char buf[150];
fgets(buf, sizeof buf, stdin);
while(!feof(stdin))
{
switch(buf[0])
{
case '0': insert(T, buf+2); break;
case '1': del(T, buf+2); break;
case '2': printf("%d\n",app(T, buf+2)); break;
case '3': printf("%d\n",pre(T, buf+2)); break;
}
fgets(buf, sizeof buf, stdin);
}
}