#include #include #include using namespace std; struct Trie { #define SIGMA 26 int cnt, nrfii; Trie *fiu[SIGMA]; Trie() { cnt = 0; nrfii = 0; memset(fiu, 0 ,sizeof(fiu)); } }; Trie *head = new Trie(); void add(Trie *node, int len, string &s) { if(len == s.length()) { node->cnt++; return; } if(node->fiu[s[len]-'a'] == NULL) { node->fiu[s[len]-'a'] = new Trie(); node->nrfii++; } add(node->fiu[s[len]-'a'], len+1, s); } int find(Trie *node, int len, string &s) { if(len == s.length()) { return node->cnt; } if(node->fiu[s[len]-'a'] == NULL) { return 0; } return find(node->fiu[s[len]-'a'], len+1, s); } bool remove(Trie *node, int len, string &s) { if(len == s.length()) { node->cnt--; } else if(remove(node->fiu[s[len]-'a'], len+1, s)) { node->nrfii--; node->fiu[s[len]-'a'] = NULL; } if(node->nrfii == 0 && node->cnt == 0 && node != head) { delete node; return true; } return false; } int prefix(Trie *node, int len, string &s) { if(len == s.length() || node->fiu[s[len]-'a'] == NULL) { return 0; } return 1 + prefix(node->fiu[s[len]-'a'], len+1, s); } int main() { freopen("trie.in", "r", stdin); freopen("trie.out", "w", stdout); string s; int x; char str[50]; while(!feof(stdin)) { scanf("%d %s\n", &x, str); s = str; if(x == 0) { add(head, 0, s); } else if(x == 1) { remove(head, 0, s); } else if(x == 2) { printf("%d\n", find(head, 0, s)); } else if(x == 3) { printf("%d\n", prefix(head, 0, s)); } } return 0; }