Pagini recente » Diferente pentru olimpici intre reviziile 133 si 134 | Atasamentele paginii rar33 | Istoria paginii olimpici | Cod sursa (job #200046) | Cod sursa (job #2018656)
#include <cstdio>
#include <algorithm>
using namespace std;
const int sigma = 26;
const int nmax = 20;
struct Trie {
int term;
int nf;
Trie* fii[sigma];
};
Trie* root;
char str[1 + nmax];
void add(Trie* nod, char *s) {
if(*s == '\0') {
nod->term ++;
return;
}
if(nod->fii[*s - 'a'] == NULL) {
nod->fii[*s - 'a'] = new Trie();
nod->nf ++;
}
add(nod->fii[*s - 'a'], s + 1);
}
bool del(Trie* nod, char *s) {
if(*s == '\0') {
nod->term --;
} else if(del(nod->fii[*s - 'a'], s + 1)) {
//delete nod->fii[*s - 'a'];
nod->fii[*s - 'a'] = NULL;
nod->nf --;
}
if(nod->term == 0 && nod->nf == 0 && nod != root) {
delete nod;
//nod = NULL;
return 1;
}
return 0;
}
int apar(Trie* nod, char *s) {
if(*s == '\0') {
return nod->term;
}
if(nod->fii[*s - 'a'] == NULL) {
return 0;
}
apar(nod->fii[*s - 'a'], s + 1);
}
int pref(Trie* nod, char *s, int h = 0) {
if(*s == '\0' || nod->fii[*s - 'a'] == NULL) {
return h;
}
pref(nod->fii[*s - 'a'], s + 1, h + 1);
}
int main() {
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
int n;
root = new Trie();
while(scanf("%d", &n) != EOF) {
scanf("%s", &str);
if(n == 0) {
add(root, str);
} else if(n == 1) {
del(root, str);
} else if(n == 2) {
printf("%d\n", apar(root, str));
} else {
printf("%d\n", pref(root, str));
}
}
return 0;
}