Cod sursa(job #1066032)

Utilizator roby2001Sirius roby2001 Data 23 decembrie 2013 22:44:17
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
/*
    Keep It Simple!
*/
 
#include<stdio.h>

#define DictionarySize 30

struct node
{
	int v;
	node *next[DictionarySize];

	node() 
	{
		v = 0;
		for( int i=0; i<=DictionarySize; i++)
			next[i] = NULL;
	}
};

node *tree = new node;

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()
{
	freopen("trie.in","r",stdin);
	freopen("trie.out","w",stdout);

	int x;
	char s[30];


	do
	{

	    scanf("%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(stdin) );

	tree = NULL;

	return 0;
}