Pagini recente » Cod sursa (job #2227162) | Cod sursa (job #2644487) | Cod sursa (job #474689) | Cod sursa (job #1623788) | Cod sursa (job #1065699)
#include <cstdio>
#include <string>
using namespace std;
#define MAXN 26
typedef struct trie {
int words, prefix;
trie *child[MAXN];
} trie;
trie *t = new trie;
void read() {
freopen( "trie.in", "r", stdin );
freopen( "trie.out", "w", stdout );
}
void add(char *s, trie *tree) {
if (s[0] < 'a' || s[0] > 'z') {
tree -> words++;
} else {
int index = s[0] - 'a';
if(!tree -> child[index])
tree -> child[index] = new trie;
tree -> prefix++;
add(s + 1, tree -> child[index]);
}
}
trie* remove(char *s, trie *tree) {
if (s[0] < 'a' || s[0] > 'z') {
tree -> words--;
} else {
int index = s[0] - 'a';
tree -> prefix--;
if(tree -> child[index] == 0)
return tree;
tree -> child[index] = remove(s + 1, tree -> child[index]);
}
if (tree -> words == 0 && tree -> prefix == 0)
return 0;
return tree;
}
int search_words(char *s, trie *tree) {
if (s[0] < 'a' || s[0] > 'z') {
return tree -> words;
} else {
int index = s[0] - 'a';
if (!tree -> child[index])
return 0;
else
return search_words(s + 1, tree -> child[index]);
}
}
int search_prefixes(char *s, trie *tree, int *rezult) {
if (s[0] < 'a' || s[0] > 'z') {
return *rezult;
} else {
int index = s[0] - 'a';
if (!tree -> child[index])
return 0;
else{
(*rezult)++;
return search_prefixes(s + 1, tree -> child[index], rezult);
}
}
}
void solve() {
char s[26];
int k, r;
while(scanf("%d %s", &k, s) == 2) {
switch(k){
case 0: add(s, t); break;
case 1: remove(s, t); break;
case 2: printf("%d\n", search_words(s, t)); break;
case 3: r = 0; printf("%d\n", search_prefixes(s, t, &r)); break;
}
}
}
int main() {
read();
solve();
return 0;
}