Cod sursa(job #923446)

Utilizator taigi100Cazacu Robert taigi100 Data 23 martie 2013 17:02:07
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include<stdio.h>
#include<string.h>
struct node
{
	int words;
	int sons;
	node *edges[26];

	node()
	{
		words=sons=0;
		memset(edges,0,sizeof(edges));
	}
};

node *trie=new node;
char k;

void addWord(node*,char *word);
int deleteWord(node*,char*);
int countWords(node*,char*);
int countPrefixes(node*,char*,int);
int main()
{
    freopen("trie.in","r",stdin);
	freopen("trie.out","w",stdout);


	char pword[32];
	fgets(pword,32,stdin);
	while(!feof(stdin))
	{
		switch(pword[0])
		{
			case '0':
				addWord(trie,pword+2);
				break;
			case '2':
				printf("%d\n",countWords(trie,pword+2));
				break;
			case '3':
				printf("%d\n",countPrefixes(trie,pword+2,0));
				break;
			case '1':
				deleteWord(trie,pword+2);
				break;
		}
		fgets(pword,32,stdin);
	}
}


int countPrefixes(node *x,char *word,int z)
{
	k=*word-'a';
    if ( *word == '\n' || x->edges[k] == 0 )
		return z;
	return countPrefixes(x->edges[k],word+1,z+1);
}

int countWords(node *x,char *word)
{
	k=*word-'a';
	if( *word== '\n' )
		return x->words;
    if( x->edges[k] )
		return countWords( x->edges[k] , word+1 );
	return 0;
}

int deleteWord(node *x,char *word)
{
   if( *word=='\n' )
	   x->words--;
   else if (deleteWord( x->edges[*word-'a'],word+1) )
   {
	   x->edges[*word-'a'] = 0;
	   x->sons-=1;
   }
   if (  x->words == 0 && x->sons == 0 && x != trie )
   { delete x; return 1; }
   return 0;
}
void addWord(node *x,char *word)
{
	if( (*word) == '\n' )
	{	x->words+=1; return; }
     
	if( x->edges[*word-'a'] == 0 )
	{
		x->edges[*word-'a']=new node;
		x->sons++;
	}
	
	addWord(x->edges[*word-'a'],word+1);    
}