Cod sursa(job #392135)

Utilizator marinaMarina Horlescu marina Data 6 februarie 2010 20:01:04
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <stdio.h>

struct Trie
{
	Trie *next['z'-'a'];
	int info;
	int ncopii;
	
	Trie()
	{
		int i;
		for(i = 0; i <= 'z'-'a'; ++i)
			next[i] = NULL;
		info = ncopii = 0;
	}
}*root;

Trie* insert(Trie *root, char *word)
{
	if(root == NULL) root = new Trie();
	if(*word == NULL)
	{
		++(root -> info);
		return root;
	}
	++(root->ncopii);
	root->next[*word - 'a'] = insert(root->next[*word - 'a'], word + 1);
	return root;
}

Trie* del(Trie *root, char *a)
{
	if(root == NULL) return root;
	if(*a == NULL)
	{
		if(root -> info <= 0) return root;
		root -> info--;
		if(root->info == 0 && root->ncopii == 0) 
		{
			delete root;
			return NULL;
		}			
		return root;
	}
	if((root->next[*a - 'a'] = del(root->next[*a - 'a'], a+1)) == NULL) 
	{
		--(root->ncopii);
		if(root->info == 0 && root->ncopii == 0) 
		{
			delete root;
			return NULL;
		}
		return root;
	}
	return root;
}


int count(Trie *root, char *a)
{
	if(root == NULL) return 0;
	if(*a == NULL) return root->info;
	return count(root->next[*a - 'a'], a + 1);
}

int prefix(Trie *root, char *a, int nr)
{
	if(root == NULL || *a == NULL) return nr - 1;
	return prefix(root->next[*a - 'a'], a+1, nr+1);
}

int main()
{
	freopen("trie.in", "r", stdin);
	freopen("trie.out", "w", stdout);
	
	Trie *t = NULL;
	root = new Trie();
	
	while(!feof(stdin))
	{
		int oper;
		char a[25];
		scanf("%d %s\n", &oper, a);
		if(oper == 0) insert(root, a);
		else if(oper == 1) del(root, a);
		else if(oper == 2) printf("%d\n", count(root, a));
		else if(oper == 3) printf("%d\n", prefix(root, a, 0));
	}
	return 0;
}