Cod sursa(job #2512949)

Utilizator radustn92Radu Stancu radustn92 Data 21 decembrie 2019 23:51:00
Problema Trie Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

const int GAMMA = 26;

struct trieNode {
	trieNode* children[GAMMA];

	int endingWords, passingWords;

	trieNode() {
		for (int i = 0; i < GAMMA; i++) {
			children[i] = NULL;
		}
		// memset(children, -1, sizeof(children));
		endingWords = passingWords = 0;
	}
};

trieNode* root = new trieNode();

void insertInTrie(trieNode* node, string& word, int pos) {
	node -> passingWords++;
	if (pos == word.size()) {
		node -> endingWords++;
		return;
	}

	int nextCharacter = word[pos] - 'a';
	if (node -> children[nextCharacter] == NULL) {
		node -> children[nextCharacter] = new trieNode();
	}
	insertInTrie(node -> children[nextCharacter], word, pos + 1);
}

void deleteFromTrie(trieNode* node, string& word, int pos) {
	node -> passingWords--;
	if (pos == word.size()) {
		node -> endingWords--;
		return;
	}

	int nextCharacter = word[pos] - 'a';
	deleteFromTrie(node -> children[nextCharacter], word, pos + 1);
}

int printWordApparitions(trieNode* node, string& word, int pos) {
	if (pos == word.size()) {
		return node -> endingWords;
	}

	int nextCharacter = word[pos] - 'a';
	if (node -> children[nextCharacter] == NULL) {
		return 0;
	}
	return printWordApparitions(node -> children[nextCharacter], word, pos + 1);
}

int longestCommonPrefix(trieNode* node, string& word, int pos) {
	if (node == NULL || node -> passingWords == 0 || pos == word.size()) {
		return pos;
	}

	int nextCharacter = word[pos] - 'a';
	return longestCommonPrefix(node -> children[nextCharacter], word, pos + 1);
}

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

	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	int opType;
	string word;

	while (cin >> opType >> word) {
		switch(opType) {
			case 0:
				insertInTrie(root, word, 0);
				break;
			case 1:
				deleteFromTrie(root, word, 0);
				break;
			case 2:
				printf("%d\n", printWordApparitions(root, word, 0));
				break;
			case 3:
				printf("%d\n", longestCommonPrefix(root, word, 0) - 1);
				break;
		}
	}
	return 0;
}