Pagini recente » Cod sursa (job #1784002) | Cod sursa (job #879044) | Cod sursa (job #1462864) | Cod sursa (job #1189109) | Cod sursa (job #1160802)
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
const int MAX = 100000;
struct Trie {
int sons [26];
int father, count, weight;
Trie () {
int i;
father = count = weight = 0;
for (i = 0; i <= 25; i ++)
sons [i] = 0;
}
Trie (int x) {
int i;
father = x;
count = weight = 0;
for (i = 0; i <= 25; i ++)
sons [i] = 0;
}
};
Trie trie [MAX];
char s [25];
int l, u = 0;
stack <int> st;
void add () {
int node = 1, i;
for (i = 0; i < l; i ++) {
++ trie [node].weight;
if (trie [node].sons [s [i] - 'a'] == 0) {
if (st.empty ()) {
trie [++ u] = Trie (node);
trie [node].sons [s [i] - 'a'] = u;
}
else {
trie [st.top ()] = Trie (node);
trie [node].sons [s [i] - 'a'] = st.top ();
st.pop ();
}
}
node = trie [node].sons [s [i] - 'a'];
}
++ trie [node].weight;
++ trie [node].count;
}
void erase (int node, int i) {
if (i == l) {
-- trie [node].count;
-- trie [node].weight;
if (node != 1 && trie [node].weight == 0) {
trie [trie [node].father].sons [s [i - 1] - 'a'] = 0;
st.push (node);
}
return;
}
erase (trie [node].sons [s [i] - 'a'], i + 1);
--trie [node].weight;
if (node != 1 && trie [node].weight == 0) {
trie [trie [node].father].sons [s [i] - 'a'] = 0;
st.push (node);
}
}
int find () {
int node, i;
node = 1;
for (i = 0; i < l && node; i ++)
node = trie [node].sons [s [i] - 'a'];
return node;
}
int query () {
int node = 1, i;
for (i = 0; i < l && node; i ++)
node = trie [node].sons [s [i] - 'a'];
if (i == l && node)
return l;
else return i - 1;
}
int main () {
int type, node;
char space;
freopen ("trie.in", "r", stdin);
freopen ("trie.out", "w", stdout);
trie [++ u] = Trie ();
while (scanf ("%d", &type) != EOF) {
scanf ("%c", &space);
gets (s);
l = strlen (s);
if (type == 0)
add ();
else
if (type == 1)
erase (1, 0);
else
if (type == 2) {
node = find ();
if (node != 0)
printf ("%d\n", trie [node].count);
else printf ("0\n");
}
else
printf ("%d\n", query ());
}
return 0;
}