Cod sursa(job #1117732)

Utilizator anaid96Nasue Diana anaid96 Data 23 februarie 2014 19:21:13
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.86 kb
#include<stdio.h>
#include<string.h>

using namespace std;

FILE *in,*out;

//definitii
#define letter *word-'a'

//constante
const int sz=20;
const int alf=26;

//structuri
struct trie_t
{
	int words;
	int sons;
	trie_t *son[alf];
	
	trie_t()
	{
		words = sons = 0;
		memset(son,'\0',sizeof(son));
	}	
};	

//functii
void insert(trie_t *node, char * word);
bool erase(trie_t *node, char * word);
int query(trie_t *node, char * word);
int prefix(trie_t *node, char * word,int lenght=0);

//variabile
char currentWord[sz];
int type;
trie_t * root=new trie_t;

int main(void)
{
	in=fopen("trie.in","rt");
	out=fopen("trie.out","wt");
	
	for(;;)
	{
		fscanf(in,"%d",&type);
		fscanf(in,"%s",currentWord);
		if(feof(in))
			break;
		if(type)
		{
			if(type==1)
			{
				erase(root,currentWord);
			}
			else
				if(type==2)
				{
					fprintf(out,"%d\n",query(root,currentWord));
				}
				else
				{
					fprintf(out,"%d\n",prefix(root,currentWord));
				}	
		}
		else
		{
			insert(root,currentWord);
		}
	}
}

void insert(trie_t *node, char *word)
{
	if(!*word)
	{
		node->words++;
		return;
	}
	
	if(!node->son[letter])
	{
		node->sons++;
		node->son[letter]=new trie_t;
	}	
	insert(node->son[letter],word+1);
}

bool erase(trie_t *node, char *word)
{
	if(!*word)
	{
		--node->words;
	}
	else
	
	if(erase(node->son[letter],word+1))
	{
		--node->sons;
		node->son[letter]='\0';
	}	
	
	if(node==root || node->words || node->sons)
		return false;
	delete node;
	return true;
}
int query(trie_t *node, char *word)
{
	if(!*word)
		return node->words;
	
	if(node->son[letter])
		return query(node->son[letter],word+1);
	
	return 0;
}

int prefix(trie_t *node, char *word,int lenght)
{
	if(!*word || !node->son[letter])
		return lenght;
	return prefix(node->son[letter],word+1,lenght+1);
}