Pagini recente » Cod sursa (job #1883632) | Cod sursa (job #971765) | Cod sursa (job #2502195) | Cod sursa (job #2371288) | Cod sursa (job #1787578)
#include <bits/stdc++.h>
#define Nmax 2000002
#define Lmax 22
FILE *fin = freopen("trie.in", "r", stdin);
FILE *fout = freopen("trie.out", "w", stdout);
using namespace std;
int N;
struct nod
{
char ch;
int s, b;
int ap, aw;
} T[Nmax];
void insert_w(int node, char *word)
{
int bro, j;
if(*word == 0)
{
++ T[node].aw;
return;
}
for(j = T[node].s; j; j = T[j].b)
if(T[j].ch == *word)
{
++ T[j].ap;
node = j;
break;
}
else bro = j;
if(j == 0)
{
T[N += 1].ch = *word;
T[N].ap = 1;
if(!T[node].s)
T[node].s = N;
else T[bro].b = N;
node = N;
}
insert_w(node, word + 1);
}
void erase_w(int node, char *word)
{
int j;
if(*word == 0)
{
-- T[node].aw;
return;
}
for(j = T[node].s; j; j = T[j].b)
if(T[j].ch == *word)
{
if(T[j].ap > 0)
-- T[j].ap;
node = j;
break;
}
erase_w(node, word + 1);
}
int appearance(int node, char *word)
{
bool f = 0;
if(*word == 0)
return T[node].aw;
for(int j = T[node].s; j; j = T[j].b)
if(T[j].ch == *word)
{
f = 1;
node = j;
break;
}
if(!f)
return 0;
else
appearance(node, word + 1);
}
int lenght_prefix(int node, char *word, int depth)
{
bool f = 0;
if(*word == 0)
return depth;
for(int j = T[node].s; j; j = T[j].b)
if(T[j].ch == *word && T[j].ap > 0)
{
f = 1;
node = j;
break;
}
if(!f)
return depth;
else lenght_prefix(node, word + 1, depth + 1);
}
int main()
{
int c;
char word[Lmax];
while(scanf("%d ", &c) != EOF)
{
gets(word);
if(c == 0) insert_w(0, word);
if(c == 1) erase_w(0, word);
if(c == 2) printf("%d\n", appearance(0, word));
if(c == 3) printf("%d\n", lenght_prefix(0, word, 0));
}
return 0;
}