Pagini recente » Cod sursa (job #1650985) | Cod sursa (job #1731387) | Cod sursa (job #2628098) | Cod sursa (job #1376875) | Cod sursa (job #1473746)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct trie {
int n;
char dim;
struct trie *next[26];
} TrieCell, *Trie;
Trie t;
void add (const char *s) {
Trie current = t;
while (*s != '\0') {
if (!current->next[*s-'a']) {
current->next[*s-'a'] = (Trie) calloc(1, sizeof(TrieCell));
++current->dim;
}
current = current->next[*s-'a'];
++s;
}
++current->n;
}
void remove (Trie *current, const char *s) {
if (*s == '\0') {
--(*current)->n;
if (!(*current)->n && !(*current)->dim) {
free(*current);
(*current) = NULL;
}
return;
}
remove(&(*current)->next[*s-'a'], s+1);
if (!(*current)->next[*s-'a']) {
--(*current)->dim;
if (!(*current)->n && !(*current)->dim) {
free(*current);
(*current) = NULL;
}
}
}
int count (const char *s) {
Trie current = t;
while (*s != '\0') {
if (!current->next[*s-'a']) {
return 0;
}
current = current->next[*s-'a'];
++s;
}
return current->n;
}
int prefixLen (const char *s) {
Trie current = t;
int i = 0;
while (*s != '\0') {
if (current->next[*s-'a']) {
current = current->next[*s-'a'];
} else {
break;
}
++i;
++s;
}
return i;
}
int main(void) {
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
t = (Trie) calloc(1, sizeof(TrieCell));
char buffer[1000];
while (fgets(buffer, 1000, stdin)) {
buffer[strlen(buffer)-1] = '\0';
char op = buffer[0];
switch (op) {
case '0': add(buffer+2); break;
case '1': remove(&t, buffer+2); break;
case '2': printf("%d\n", count(buffer+2)); break;
case '3': printf("%d\n", prefixLen(buffer+2)); break;
}
}
return 0;
}