Pagini recente » Cod sursa (job #2392552) | Cod sursa (job #53404) | Cod sursa (job #332995) | Cod sursa (job #577601) | Cod sursa (job #2039756)
#include <cstdio>
#include <cstring>
const int MAX_N = 20;
const int SIGMA = 26;
class Trie {
public:
int words;
int sons;
Trie* edges[1 + SIGMA];
Trie() {
words = sons = 0;
for (int i = 1; i <= SIGMA; i++) {
edges[i] = NULL;
}
}
void addWord(char s[], int pos, int length) {
if (pos == length) {
words++;
} else {
char first = s[pos];
if (edges[first - 'a' + 1] == NULL) {
edges[first - 'a' + 1] = new Trie;
sons++;
}
edges[first - 'a' + 1]->addWord(s, pos + 1, length);
}
}
bool deleteWord(Trie* t, char s[], int pos, int length) {
if (pos == length) {
words--;
} else {
char first = s[pos];
bool aux = edges[first - 'a' + 1]->deleteWord(t, s, pos + 1, length);
if (aux == 1) {
sons--;
edges[first - 'a' + 1] = NULL;
}
}
if (sons == 0 && words == 0 && this != t) {
delete this;
return 1;
}
return 0;
}
int countWords(char s[], int length) {
Trie* aux = this;
for (int i = 0; i < length; ++i) {
char k = s[i];
if (aux->edges[k - 'a' + 1] == NULL) {
return 0;
}
aux = aux->edges[k - 'a' + 1];
}
return aux->words;
}
int prefixes(char s[], int length) {
Trie* aux = this;
for (int i = 0; i < length; i++) {
char k = s[i];
if (aux->edges[k - 'a' + 1] == NULL) {
return i;
}
aux = aux->edges[k - 'a' + 1];
}
}
};
int main() {
freopen ("trie.in", "r", stdin);
freopen ("trie.out", "w", stdout);
int type;
Trie* t;
t = new Trie;
char s[5 + MAX_N];
while (scanf("%d", &type) != EOF) {
getc(stdin);
scanf("%s", s);
int length = strlen(s);
if (type == 0) {
t->addWord(s, 0, length);
} else if (type == 1) {
bool aux = t->deleteWord(t, s, 0, length);
} else if (type == 2) {
printf("%d\n", t->countWords(s, length));
} else if (type == 3) {
printf("%d\n", t->prefixes(s, length));
}
}
return 0;
}