Pagini recente » Cod sursa (job #1442474) | Cod sursa (job #208508) | Cod sursa (job #259119) | Cod sursa (job #2552035) | Cod sursa (job #1476412)
#include <cstdio>
#include <cstring>
const int GAMMA = 26;
struct node {
int pass, end;
node* children[GAMMA];
node() {
pass = end = 0;
memset(children, 0, sizeof(children));
}
};
class trie {
node* root;
public:
trie() {
root = new node();
}
void trieInsert(char* s) {
trieInsert(root, s);
}
void trieDelete(char* s) {
trieDelete(root, s);
}
int trieCnt(char* s) {
return trieCnt(root, s);
}
int trieLcp(char* s) {
return trieLcp(root, s);
}
private:
void trieInsert(node*, char*);
void trieDelete(node*, char*);
int trieCnt(node*, char*);
int trieLcp(node*, char*);
};
trie* x = new trie();
void trie::trieInsert(node* curr, char* s) {
curr -> pass++;
if (*s == '\0') {
curr -> end++;
return ;
}
if (curr -> children[*s - 'a'] == 0) {
curr -> children[*s - 'a'] = new node();
}
trieInsert(curr -> children[*s - 'a'], s + 1);
}
void trie::trieDelete(node* curr, char* s) {
curr -> pass--;
if (*s == '\0') {
curr -> end--;
return ;
}
trieDelete(curr -> children[*s - 'a'], s + 1);
if ((curr -> children[*s - 'a']) -> pass == 0) {
delete curr -> children[*s - 'a'];
curr -> children[*s - 'a'] = 0;
}
}
int trie::trieCnt(node* curr, char* s) {
if (*s == '\0') {
return curr -> end;
}
if (curr -> children[*s - 'a'] == 0) {
return 0;
}
return trieCnt(curr -> children[*s - 'a'], s + 1);
}
int trie::trieLcp(node* curr, char* s) {
if (*s == '\0' || curr -> children[*s - 'a'] == 0) {
return 0;
}
return 1 + trieLcp(curr -> children[*s - 'a'], s + 1);
}
void solve() {
int type;
char word[GAMMA];
while (scanf("%d%s", &type, word) == 2) {
switch (type) {
case 0: {
// add word
x -> trieInsert(word);
break;
}
case 1: {
x -> trieDelete(word);
break;
}
case 2: {
printf("%d\n", x -> trieCnt(word));
break;
}
case 3: {
printf("%d\n", x -> trieLcp(word));
break;
}
}
}
}
int main() {
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
solve();
return 0;
}