Cod sursa(job #791434)

Utilizator ucc_5Usurelu Catalin ucc_5 Data 24 septembrie 2012 01:40:13
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.07 kb
#include <fstream>
#include <cstring>
#include <sstream>

#define MAX_COMM_SIZE 23
#define MAX_WORD_SIZE 20
#define ALPHABET_SIZE 'z' - 'a'  + 1
#define charToIndex(x) x - 'a'

using namespace std;

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

class TrieNode
{
	private:

		TrieNode* letter[ALPHABET_SIZE];
		int nr_words;
		int nr_kids;

	public:

		TrieNode()
		{
			nr_words = 0;
			nr_kids = 0;
			memset(letter, 0, sizeof(letter));
		}

		void insert(char* word)
		{
			if(letter[charToIndex(*word)] == NULL)
			{
				letter[charToIndex(*word)] = new TrieNode;
				nr_kids++;
			}

			if(strlen(word) == 1)
				letter[charToIndex(*word)] -> nr_words++;
			else
				letter[charToIndex(*word)] -> insert(word + 1);

		}

		void erase(char* word)
		{
			if(strlen(word) != 1)
				letter[charToIndex(*word)] -> erase(word + 1);
			else
				letter[charToIndex(*word)] -> nr_words--;

			if (letter[charToIndex(*word)] -> nr_words == 0
				&& letter[charToIndex(*word)] -> nr_kids == 0)
			{
				delete letter[charToIndex(*word)];
				letter[charToIndex(*word)] = NULL;
				nr_kids--;
			}
		}

		int word_count(char* word)
		{
			if(letter[charToIndex(*word)] == NULL)
				return 0;
				
			if(strlen(word) == 1)
				return letter[charToIndex(*word)] -> nr_words;
			else
				return letter[charToIndex(*word)] -> word_count(word + 1);
		}

		int longest_common_prefix(char* word)
		{
			//daca nu exista returneaza direct 0
			if(letter[charToIndex(*word)] == NULL || strlen(word) == 0)
				return 0;
			
			return 1 + letter[charToIndex(*word)] -> longest_common_prefix(word + 1);
		}
};


int main()
{
	TrieNode* trie_root = new TrieNode;
	char command[MAX_COMM_SIZE], word[MAX_WORD_SIZE];
	int comm;
	stringstream buffer;

	while(f.getline(command, MAX_COMM_SIZE))
	{
		buffer.str(command);
		buffer >> comm >> word;
		buffer.clear();

		switch(comm)
		{
		case 0:
			trie_root -> insert(word);
			break;
		case 1:
			trie_root -> erase(word);
			break;
		case 2:
			g << trie_root -> word_count(word) << '\n';
			break;
		case 3:
			g << trie_root -> longest_common_prefix(word) << '\n';
		}
	}

	return 0;
}