Pagini recente » Cod sursa (job #3265064) | Cod sursa (job #1333944) | Cod sursa (job #185617) | Cod sursa (job #2194614) | Cod sursa (job #1750604)
#include <stdio.h>
#include <cstdio>
#include <cstring>
struct Trie {
int cnt, nrfii;
Trie *fiu[ 26 ];
Trie() {
cnt = nrfii = 0;
memset(fiu, 0, sizeof(fiu)); //wtf is dis?
}
};
Trie *T = new Trie;
void ins(Trie *nod, char *s) {
if (*s == '\n') {
nod->cnt ++;
return;
}
if (!nod->fiu[*s - 'a']) {
nod->fiu[*s - 'a'] = new Trie;
nod->nrfii ++;
}
ins(nod->fiu[*s - 'a'], s + 1);
}
bool del(Trie *nod, char *s) {
if (*s == '\n')
nod->cnt --;
else if (del(nod->fiu[*s - 'a'], s + 1)) {
nod->fiu[*s - 'a'] = 0; //de ce 0? nu e int
nod->nrfii --;
}
if (nod->cnt == 0 && nod->nrfii == 0 && nod != T) {
delete nod;
return true;
}
return false;
}
int count(Trie *nod, char *s) {
if (*s == '\n')
return nod->cnt;
if (!nod->fiu[*s - 'a'])
return 0;
else return count(nod->fiu[*s - 'a'], s + 1);
}
int longest(Trie *nod, char *s) {
if (*s == '\n' || !nod->fiu[*s - 'a'])
return 0;
else return (1 + longest(nod->fiu[*s - 'a'], s + 1));
}
int main() {
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
int op;
char line[32];
do {
fgets(line, 32, stdin);
if (line[0] == '0')
ins(T, line + 2);
else if (line[0] == '1')
del(T, line + 2);
else if (line[0] == '2')
printf("%d\n", count(T, line + 2));
else printf("%d\n", longest(T, line + 2));
} while (!feof(stdin));
return 0;
}