Cod sursa(job #2655280)

Utilizator akumariaPatrascanu Andra-Maria akumaria Data 3 octombrie 2020 20:07:47
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.15 kb
#include <cstdio>
#include <cstring>

using namespace std;

struct Trie {
	int words, childrenNo;
	Trie * children[26];

	Trie() {
		words = childrenNo = 0;
		memset(children, 0, sizeof(children));
	}
};

Trie * root;


void addWord(Trie * vertex, char * word, int n) {
	if (n == 0) {
		++ vertex->words;
		return;
	}

	Trie * currentSon = vertex->children[word[0] - 'a'];
	if (currentSon == 0) {
		vertex->children[word[0] - 'a'] = new Trie;
		currentSon = vertex->children[word[0] - 'a'];
		++ vertex->childrenNo;
	}

	addWord(currentSon, word + 1, n - 1);
}


bool deleteWord(Trie * vertex, char * word, int n) {
	if (n == 0) {
		-- vertex->words;
	}
	else {
		Trie * currentSon = vertex->children[word[0] - 'a'];
		if (currentSon)
			if (deleteWord(currentSon, word + 1, n - 1)) {
				delete currentSon;
				vertex->children[word[0] - 'a'] = 0;
				-- vertex->childrenNo;
			}
	}

	if (vertex->words == 0 && vertex->childrenNo == 0)
		return true;
	return false;
}


int findWord(Trie * vertex, char * word, int n) {
	if (n == 0)
		return vertex->words;

	Trie * currentSon =  vertex->children[word[0] - 'a'];
	if (currentSon)
		return findWord(currentSon, word + 1, n - 1);

	return 0;
}


int findPrefix(Trie * vertex, char * word, int n, int current_depth) {
	if (n == 0)
		return current_depth;

	Trie * currentSon = vertex->children[word[0] - 'a'];
	if (currentSon)
		return findPrefix(currentSon, word + 1, n - 1, current_depth + 1);

	return current_depth;
}


int main() {
	freopen("trie.in", "r", stdin);
	freopen("trie.out", "w", stdout);

	root  = new Trie;

	char currentWord[23];
	int opType, n;

	while (! feof(stdin) && scanf("%d %s\n", &opType, &currentWord)) {
		n = strlen(currentWord);
		if (currentWord[n-1] == '\n') {
			--n;
			currentWord[n] = 0;
		}
		switch(opType) {
			case 0:
				addWord(root, currentWord, n);
				break;
			case 1:
				deleteWord(root, currentWord, n);
				break;
			case 2:
				printf("%d\n", findWord(root, currentWord, n));
				break;
			case 3:
				printf("%d\n", findPrefix(root, currentWord, n, 0));
				break;
		}
	}

	return 0;
}