Pagini recente » Cod sursa (job #1869913) | Cod sursa (job #3145777) | Cod sursa (job #679770) | Cod sursa (job #1767275) | Cod sursa (job #2512955)
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int GAMMA = 26;
struct trieNode {
trieNode* children[GAMMA];
int endingWords, passingWords;
trieNode() {
memset(children, 0, 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);
}
bool deleteFromTrie(trieNode* node, string& word, int pos) {
node -> passingWords--;
if (pos == word.size()) {
node -> endingWords--;
return node -> passingWords == 0;
}
int nextCharacter = word[pos] - 'a';
if (deleteFromTrie(node -> children[nextCharacter], word, pos + 1)) {
free(node -> children[nextCharacter]);
node -> children[nextCharacter] = NULL;
}
return node -> passingWords == 0;
}
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) {
return pos - 1;
}
if (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) );
break;
}
}
return 0;
}