Pagini recente » Cod sursa (job #1317708) | Cod sursa (job #1700388) | Cod sursa (job #2442604) | Cod sursa (job #738758) | Cod sursa (job #1066005)
/*
Keep It Simple!
*/
#include<stdio.h>
#define DictionarySize 28
struct node
{
int v;
node *next[DictionarySize];
node()
{
v = 0;
for( int i=0; i<=DictionarySize; i++)
next[i] = NULL;
}
} *tree;
void Init()
{
tree = new node;
tree -> v = 0;
for(int i=0;i<=DictionarySize;i++)
tree->next[i] = NULL;
}
void AddWord( char *s, node* crt )
{
if ( s[0] == 0 )
{
crt->v++;
return;
}
else
{
if(!crt->next[s[0]-'a'])
crt->next[s[0]-'a'] = new node;
AddWord(s+1,crt->next[s[0]-'a']);
}
}
int PrintWordsNumber( char *s, node* crt )
{
if ( s[0] == 0 )
return crt -> v;
else
{
if(!crt->next[s[0]-'a'])
return 0;
PrintWordsNumber(s+1,crt->next[s[0]-'a']);
}
}
int LongestPrefix( char *s, node* crt, int level )
{
if ( s[0] == 0 )
return level;
else
{
if(!crt->next[s[0]-'a'])
return level;
LongestPrefix(s+1,crt->next[s[0]-'a'],level+1);
}
}
bool isEmpty( node* crt )
{
if( crt -> v > 0 )
return 0;
for(int i=0; i<=DictionarySize; i++)
if(crt->next[i]!=NULL)
return 0;
return 1;
}
void DeleteWord( char *s, node* crt)
{
if ( s[0] == 0 )
{
crt -> v--;
return;
}
else
{
if(!crt->next[s[0]-'a'])
return;
DeleteWord(s+1,crt->next[s[0]-'a']);
if(isEmpty(crt->next[s[0]-'a']))
crt->next[s[0]-'a'] = NULL;
}
}
int main()
{
FILE *f = fopen("trie.in","r");
freopen("trie.out","w",stdout);
int x;
char s[25];
tree = new node();
do
{
fscanf(f,"%d %s",&x,s);
if( x == 0 )
AddWord(s,tree);
else if ( x == 2 )
printf("%d\n",PrintWordsNumber(s,tree));
else if ( x == 3 )
printf("%d\n",LongestPrefix(s,tree,0));
else if ( x == 1 )
DeleteWord(s,tree);
}while( !feof(f) );
tree = NULL;
return 0;
}