Pagini recente » Cod sursa (job #1662864) | Cod sursa (job #1252352) | Cod sursa (job #1948752) | Cod sursa (job #91754) | Cod sursa (job #2219926)
/**
* Worg
*/
#include <cstdio>
FILE *fin = freopen("trie.in", "r", stdin); FILE *fout = freopen("trie.out", "w", stdout);
const int TETA = 26;
const int MAX_LEN = 20 + 5;
struct TrieNode {
TrieNode *sons[TETA];
int wordCount;
TrieNode() {
this->wordCount = 0;
for(int i = 0; i < TETA; i++) {
this->sons[i] = NULL;
}
}
};
TrieNode *root = new TrieNode;
void Insert(TrieNode *node, char *word) {
node->wordCount++;
if(*word == NULL) return;
if(node->sons[*word - 'a'] == NULL) {
node->sons[*word - 'a'] = new TrieNode;
}
Insert(node->sons[*word - 'a'], word + 1);
}
void Erase(TrieNode *node, char *word) {
node->wordCount--;
if(*word == NULL) return;
Erase(node->sons[*word - 'a'], word + 1);
}
int CountApparitions(TrieNode *node, char *word) {
if(*word == NULL) {
int answer = node->wordCount;
for(int i = 0; i < TETA; i++) {
if(node->sons[i] != NULL) {
answer -= node->sons[i]->wordCount;
}
}
return answer;
}
if(node->sons[*word - 'a'] == NULL) {
return 0;
}
return CountApparitions(node->sons[*word - 'a'], word + 1);
}
int MaxCommonLength(TrieNode *node, char *word, int currentLength) {
if(*word == NULL || node->sons[*word - 'a'] == NULL || node->sons[*word - 'a']->wordCount == 0) {
return currentLength;
} else {
return MaxCommonLength(node->sons[*word - 'a'], word + 1, currentLength + 1);
}
}
int main() {
int type;
char word[MAX_LEN];
while(scanf("%d%s", &type, word) == 2) {
if(type == 0) {
Insert(root, word);
} else if(type == 1) {
Erase(root, word);
} else if(type == 2) {
printf("%d\n", CountApparitions(root, word));
} else {
printf("%d\n", MaxCommonLength(root, word, 0));
}
}
return 0;
}