Cod sursa(job #2138901)

Utilizator Chirita_MateiChirita Matei Chirita_Matei Data 21 februarie 2018 22:49:03
Problema Trie Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb

#include <fstream>
#include <cstring>
using namespace std;
ofstream fout("trie.out");
ifstream fin("trie.in");

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

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

public:
	Trie(){
		contor = 0;
		memset(next, 0, sizeof(next));
	}

	void _insert(char* word) {
		if (*word == 0) {
			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 == 0) {
			return this->contor;
		}

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

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

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

			else {
				this->contor--;
				return (this->contor ==0);
			}
		}

		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 < 26; i++) {
					toDelete &= (son->next[i] == NULL);
				}

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

		return aux;
	}

	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[30];

	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;
}