Pagini recente » Cod sursa (job #2877468) | Cod sursa (job #3139482) | Cod sursa (job #308652) | Cod sursa (job #426960) | Cod sursa (job #2370028)
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define ADD 0
#define DELETE 1
#define COUNT 2
#define LONGEST_PREFIX 3
#define DEBUG 0
struct node {
short pass, end;
struct node **next;
};
char word[21];
int operation;
struct node* trie[26];
struct node* makeNode(char value) {
struct node* node = (struct node*) malloc(sizeof(struct node));
node->pass = 0;
node->end = 0;
node->next = (struct node**) calloc(26, sizeof(struct node*));
return node;
}
void onDelete(struct node** root, char* word, int length, int current) {
if (NULL == root || length == current) return;
int index = word[current] - 'a';
if (NULL != root[index]) {
onDelete(root[index]->next, word, length, 1 + current);
--(root[index]->pass);
if (length - 1 == current) {
--(root[index]->end);
}
if (DEBUG) printf(" %c -> passes: %d\n", word[current], root[index]->pass);
if (0 == root[index]->pass) {
free(root[index]->next);
free(root[index]);
root[index] = NULL;
}
}
}
int main() {
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
while (EOF != scanf("%d %s\n", &operation, word)) {
switch (operation) {
case ADD: {
if (DEBUG) printf("--> ADD: %s\n", word);
int length = strlen(word);
struct node** next = trie;
for (int it = 0; it < length; ++it) {
int index = word[it] - 'a';
if (DEBUG) printf(" %c -> %d\n", word[it], NULL == next[index]);
if (NULL == next[index]) {
next[index] = makeNode(word[it]);
}
++(next[index]->pass);
if (length - 1 == it) ++(next[index]->end);
next = next[index]->next;
}
break;
}
case DELETE: {
if (DEBUG) printf("--> DELETE: %s\n", word);
onDelete(trie, word, strlen(word), 0);
break;
}
case COUNT: {
if (DEBUG) printf("--> COUNT: %s\n", word);
int length = strlen(word);
struct node **next = trie;
bool nok = false;
for (int it = 0; it < length - 1; ++it) {
int index = word[it] - 'a';
if (DEBUG) printf(" %c -> %d\n", word[it], NULL == next[index]);
if (NULL == next[index]) {
nok = true;
break;
}
next = next[index]->next;
}
int lastIndex = word[length - 1] - 'a';
if (nok || NULL == next[lastIndex]) {
printf("0\n");
} else {
printf("%d\n", next[lastIndex]->end);
}
break;
}
case LONGEST_PREFIX: {
if (DEBUG) printf("--> LONGEST PREFIX: %s\n", word);
int length = strlen(word);
struct node **next = trie;
int count = 0;
int wordIndex = 0;
while (wordIndex < length && NULL != next[word[wordIndex] - 'a'] && 0 < next[word[wordIndex] - 'a']->pass) {
++count;
next = next[word[wordIndex] - 'a']->next;
++wordIndex;
}
printf("%d\n", count);
break;
}
}
}
return 0;
}