Pagini recente » Cod sursa (job #1396002) | Cod sursa (job #593819) | Cod sursa (job #1942784) | Cod sursa (job #2492520) | Cod sursa (job #1160813)
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
const int MAX = 1000000;
struct Trie {
int sons [26];
int father, count, weight;
};
Trie trie [MAX];
char s [20];
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].father = node;
trie [node].sons [s [i] - 'a'] = u;
}
else {
trie [st.top ()].father = 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);
++ u;
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;
}