Cod sursa(job #1116879)

Utilizator negrea.andreiAndrei Negrea negrea.andrei Data 22 februarie 2014 21:21:13
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.19 kb
#include<fstream>
#include<cstdlib>
using namespace std;

struct TrieNode {
	int prefixCount;
	int endCount;

	TrieNode *children[30];

	TrieNode()
	{
		prefixCount = 0;
		endCount = 0;
		for(int i = 0; i < 30; i++)
		{
			children[i] = 0;
		}
	}
};

ifstream f("trie.in");
ofstream g("trie.out");
	
int longestPrefix(TrieNode *root, char *word, int pos, int wordLength)
{
	if (pos == wordLength)
	{
		return wordLength;
	}

	if (root->children[word[pos] - 'a'] != 0)
	{
		return longestPrefix(root->children[word[pos] - 'a'], word, pos + 1, wordLength);
	}
	else
	{
		return pos;
	}
}

int countWord(TrieNode *root, char *word, int pos, int wordLength)
{
	if (pos == wordLength)
	{
		return root->endCount;
	}
	if (root->children[word[pos] - 'a'] != 0)
	{
		countWord(root->children[word[pos] - 'a'], word, pos + 1, wordLength);
	}
	else
	{
		return 0;
	}
}
void del(TrieNode *root, char *word, int pos, int wordLength)
{
	root->prefixCount--;

	if (pos == wordLength)
	{
		root->endCount--;
		return;
	}

	if (root -> children[word[pos] - 'a'] != 0)
	{
		del(root -> children[word[pos] - 'a'], word, pos + 1, wordLength);
		if (root -> children[word[pos] - 'a']->prefixCount == 0 && root -> children[word[pos] - 'a']->endCount == 0)
		{
			delete root->children[word[pos] - 'a'];
			root->children[word[pos] - 'a'] = 0;
		}
	}

}
void add(TrieNode *root, char *word, int pos, int wordLength)
{
	root->prefixCount++;

	if (pos == wordLength)
	{
		root->endCount++;
		return;
	}

	if (root -> children[word[pos] - 'a'] == 0)
	{
		root -> children[word[pos] - 'a'] = new TrieNode();
	}
	
	add(root->children[word[pos] - 'a'], word, pos + 1, wordLength);
}

int main()
{
	TrieNode root;
	while (!f.eof())
	{
		int codop = -1;
		char word[300];

		f >> codop >> word;

		if (codop == -1)
		{
			break;
		}
		if (codop == 0)
		{
			add(&root, word, 0, strlen(word));
		}
		if (codop == 1)
		{
			del(&root, word, 0, strlen(word));
		}
		if (codop == 2)
		{
			g << countWord(&root, word, 0, strlen(word)) << "\n";
		}
		if (codop == 3)
		{
			g << longestPrefix(&root, word, 0, strlen(word)) << "\n";
		}
	}

	return 0;
}