Pagini recente » Cod sursa (job #1569522) | Cod sursa (job #846741) | Cod sursa (job #2944463) | Cod sursa (job #1839363) | Cod sursa (job #1160806)
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
const int MAX = 1000000;
struct Trie {
int sons [26];
int father, count, weight;
Trie () {
}
Trie (int x) {
father = x;
}
};
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] = 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;
double size;
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 ());
}
size = sizeof (trie) / 1024 / 1024;
printf ("%lf\n", size);
return 0;
}