Pagini recente » Cod sursa (job #2667519) | Cod sursa (job #1907128) | Cod sursa (job #2573070) | Cod sursa (job #1591270) | Cod sursa (job #2655280)
#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, ¤tWord)) {
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;
}