Cod sursa(job #1150462)

Utilizator SilverGSilver Gains SilverG Data 23 martie 2014 00:42:13
Problema Trie Scor 55
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb

/*
Keep It Simple!
*/

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#include<fstream>

using namespace std;

int type;
char c[22];

struct T
{
	int NrWords,NrSons;
	T* next[27];
	T()
	{
		NrWords = NrSons = 0;
		for (int i = 0; i < 27; i++) next[i] = 0;
	};
}*Trie;

void AddToTrie(T* node,  char *str)
{
	int p = str[0] - 'a';
	if (str[0] == 0)
	{
		node->NrWords++;
		return;
	}
	else
	{
		if (!node->next[p])
		{
			node->NrSons++;
			node->next[p] = new T();
		}
		AddToTrie(node->next[p],str + 1);
	}
}

int FindWordsAppNumber(T* node, char *str)
{
	int p = str[0] - 'a';
	if (str[0] == 0)
		return node->NrWords;
	else
	{
		if (!node->next[p])
			return 0;
		return FindWordsAppNumber(node->next[p], str + 1);
	}
}

bool RemoveFromTrie(T* node, char* str)
{
	int p = str[0] - 'a';
	if (str[0] == 0)
		node->NrWords--;
	else
	{
		if (RemoveFromTrie(node->next[p], str + 1))
		{
			node->next[p] = 0;
		}
	}
	if (node->NrSons || node->NrWords)
		return 0;
	return 1;
}

int NumberOfPrefixes(T* node, char * str, int level)
{
	int p = str[0] - 'a';
	if (str[0] == 0)
		return level;
	else
	{
		if (!node->next[p])
			return level;
		return NumberOfPrefixes(node->next[p], str + 1, level + 1);
	}
}

int main()
{
	ifstream  f("trie.in");
	ofstream g("trie.out");

	Trie = new T();

	while (f >> type >> c)
	{
		if (type == 0)
			AddToTrie(Trie, c);
		else if (type == 2)
			g << FindWordsAppNumber(Trie, c) << "\n";
		else if (type == 1)
			RemoveFromTrie(Trie, c);
		else if (type == 3)
			g << NumberOfPrefixes(Trie, c, 0) << "\n";
	}
}