Cod sursa(job #2112928)

Utilizator Chirita_MateiChirita Matei Chirita_Matei Data 23 ianuarie 2018 23:18:59
Problema Trie Scor 55
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb


#include <fstream>

using namespace std;
ofstream fout("trie.out");
ifstream fin("trie.in");

class Trie {
private:
	Trie * next[100];
	int contor;

	int max(int a, int b){
		return a >= b ? a : b;
	}

public:
	Trie(){
		contor = 0;
		for (int i = 0; i <= 30; i++) {
			next[i] = NULL;
		}
	}

	void _insert(char* word) {
		if (*word == NULL) {
			this->contor++;
			return;
		}

		if (this->next[*word - 'a'] == NULL) {
			this->next[*word - 'a'] = new Trie;
		}

		this->next[*word - 'a']->_insert(word + 1);
	}

	int _count(char* word) {
		if (*word == NULL) {
			return this->contor;
		}

		if (this->next[*word - 'a'] == NULL) {
			return 0;
		}

		this->next[*word - 'a']->_count(word + 1);
	}

	bool _erase(char* word) {
		if (*word == NULL) {
			if (this->contor == 0) {
				return false;
			}

			else {
				this->contor--;
				return true;
			}
		}

		if (this->next[*word - 'a'] == NULL) {
			return false;
		}

		bool aux = this->next[*word - 'a']->_erase(word + 1);

		if (aux) {
			Trie* son = this->next[*word - 'a'];
			bool toDelete = (son->contor == 0);
			if (toDelete)
				for (int i = 0; i <= 30; i++) {
					toDelete &= (son->next[i] == NULL);
				}

			if (toDelete) {
				delete son;
				this->next[*word - 'a'] = NULL;
			}
		}
	}

	int lgPrefix(char* word, int lg) {
		if (*word == NULL) {
			return lg;

		}

		if (this->next[*word - 'a'] == NULL) {
			return lg;
		}

		return this->next[*word - 'a']->lgPrefix(word + 1, lg + 1);
	}
};

Trie *trie = new Trie();

int main()
{
	int o;
	char word[100];

	while (fin >> o >> word) {
		switch (o) {
		case 0: trie->_insert(word); break;
		case 1: trie->_erase(word); break;
		case 2: fout << trie->_count(word) << '\n'; break;
		case 3: fout << trie->lgPrefix(word, 0) << '\n'; break;
		}
	}
	return 0;
}