Cod sursa(job #715213)

Utilizator catalinb91Catalin Badea catalinb91 Data 16 martie 2012 20:51:32
Problema Trie Scor 15
Compilator cpp Status done
Runda Arhiva educationala Marime 2.24 kb
#include <fstream>
#include <iostream>

using namespace std;
#define ALPHABET_SIZE ('z' - 'a' + 1)
#define ID(ch) (ch - 'a')
#define LETTER(id) ((char)(id + 'a'))

struct Nod {
	int words;
	int prefixes;
	Nod* child[ALPHABET_SIZE];
	Nod() :
		words(0),
		prefixes(0)
	{
		for (int i = 0; i < ALPHABET_SIZE; i++)
			child[i] = NULL;
	}
	~Nod()
	{
		for (int i = 0; i < ALPHABET_SIZE; i++)
			if (child[i])
				delete child[i];
	}

	void addWord(string& word)
	{
		if (word.length() <= 0) {
			words++;
			return;
		}
		
		prefixes++;
		char key = word[0];
		word.erase(0, 1);

		if (!child[ID(key)])
			child[ID(key)] = new Nod();

		child[ID(key)]->addWord(word);
	}

	bool deleteWord(string& word)
	{
		if (word.length() <= 0) {
			words--;	
			return true;
		}

		char key = word[0];
		if (!child[ID(key)])
			return false;
		word.erase(0, 1);
		if (child[ID(key)]->deleteWord(word)) {
			prefixes--;
			if (child[ID(key)]->words <= 0 && child[ID(key)]->prefixes <= 0) {
				delete child[ID(key)];
				child[ID(key)] = NULL;
			}	
			return true;
		}
		return false;
	}

	int countWord(string& word) {
		if (word.length() <= 0)
			return words;
		char key = word[0];
		word.erase(0, 1);

		if (!child[ID(key)])
			return 0;

		return child[ID(key)]->countWord(word);
	}

	int largestPrefix(string& word, int size = 0)
	{
		if (word.length() <= 0 || prefixes < 2)
			return size;

		char key = word[0];
		word.erase(0, 1);

		if (!child[ID(key)])
			return size;

		return child[ID(key)]->largestPrefix(word, size + 1);
	}

	void display(int level = 0)
	{
		cout << " [words: " << words << " prefixes: " << prefixes << "]\n";
		for (int i = 0; i < ALPHABET_SIZE; i++) {
			if (!child[i])
				continue;
			for (int j = 0; j < level; j++)
				cout << " ";
			cout << LETTER(i);
			child[i]->display(level + 1);
		}

	}
};

int main()
{
	ifstream input("trie.in");
	ofstream output("trie.out");
// #define output cout

	Nod root;
	while (!input.eof()) {
		string word;
		int command;
		input >> command >> word;
		if (input.eof())
			break;
		if (command == 0)
			root.addWord(word);
		else if (command == 1)
			root.deleteWord(word);
		else if (command == 2)
			output << root.countWord(word) << "\n";	
		else if (command == 3)
			output << root.largestPrefix(word) << "\n";	
	}
	return 0;
}