Pagini recente » Cod sursa (job #3287292) | Cod sursa (job #3259824) | Cod sursa (job #523237) | Cod sursa (job #3271216) | Cod sursa (job #240978)
Cod sursa(job #240978)
#include <cstdio>
#include <cstring>
typedef struct noduri
{
int cuv,fii;
noduri *L[26];
noduri()
{
fii=cuv=0;
memset(L,0,sizeof(L));
}
} trie;
char w[21];
trie *T;
void insert(trie *t, char *c)
{
if (*c=='\n') t->cuv++;
else
{
int ch=*c-'a';
if (t->L[ch]==NULL)
{
t->L[ch]=new trie;
t->fii++;
}
insert(t->L[ch],c+1);
}
}
int count_words(trie *t, char *c)
{
if (*c=='\n') return t->cuv;
else
if (t->L[*c-'a']) return count_words(t->L[*c-'a'],c+1);
else return 0;
}
int count_prefix(trie *t, char *c)
{
if (*c=='\n' || t->L[*c-'a']==NULL || t->fii==0) return 0;
else
return count_prefix(t->L[*c-'a'],c+1)+1;
}
int erase(trie *t, char *c)
{
if (*c=='\n')
{
t->cuv--;
if (t->cuv==0 && t->fii==0 && t!=T)
{
delete t;
return 1;
}
else return 0;
}
else
{
if (erase(t->L[*c-'a'],c+1))
t->fii--;
if (t->cuv==0 && t->fii==0 && t!=T)
{
delete t;
return 1;
}
else return 0;
}
}
/*
int erase( trie *nod, char *s )
{
if( *s == '\n' ) nod->cuv --;
else if( erase( nod->L[ *s - 'a' ], s+1 ) )
{
nod->L[ *s - 'a' ] = 0;
nod->fii --;
}
if( nod->cuv == 0 && nod->fii == 0 && nod != T )
{
delete nod;
return 1;
}
return 0;
}
*/
int main()
{
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
T=new trie;
fgets(w,21,stdin);
while (!feof(stdin))
{
switch (w[0])
{
case '0':insert(T,w+2); break;
case '1':erase(T,w+2); break;
case '2':printf("%d\n",count_words(T,w+2)); break;
case '3':printf("%d\n",count_prefix(T,w+2)); break;
}
fgets(w,21,stdin);
}
return 0;
}