Pagini recente » Cod sursa (job #60338) | Cod sursa (job #436563) | Cod sursa (job #2102206) | Cod sursa (job #1537308) | Cod sursa (job #2770658)
#include <bits/stdc++.h>
#define NMAX 26
using namespace std;
struct Trie {
int cnt;
int ends;
Trie *t[NMAX];
Trie() {
cnt = 0;
for(int i = 0; i < NMAX; i++) {
ends = 0;
t[i] = NULL;
}
}
void add(const char *w) {
cnt ++;
if(w[0] == '\0') {
ends ++;
return ;
}
int idx = w[0] - 'a';
if(this->t[idx] == NULL) {
this->t[idx] = new Trie();
}
this->t[idx]->add(w+1);
}
void del(const char *w) {
cnt --;
if(w[0] == '\0') {
ends --;
return ;
}
int idx = w[0] - 'a';
this->t[idx]->del(w+1);
if(this->t[idx]->cnt == 0) {
delete this->t[idx];
this->t[idx] = NULL;
}
}
int count(const char *w) {
if(w[0] == '\0') {
return this->ends;
}
int idx = w[0] - 'a';
if(this->t[idx] == NULL) {
return 0;
}
return this->t[idx]->count(w+1);
}
int longestPref(const char *w) {
if(w[0] == '\0') {
return 0;
}
int idx = w[0] -'a';
if(this->t[idx] == NULL) {
return 0;
}
return 1 + this->t[idx]->longestPref(w+1);
}
};
int main()
{
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
Trie *root = new Trie();
int op;
char w[23];
while(scanf("%d %s",&op, w) != EOF) {
if(op == 0) {
root->add(w);
}else if(op == 1) {
root->del(w);
}else if(op == 2) {
printf("%d\n",root->count(w));
}else {
printf("%d\n",root->longestPref(w));
}
}
return 0;
}