Pagini recente » Cod sursa (job #264833) | Cod sursa (job #1234533) | Cod sursa (job #2839129) | Cod sursa (job #2040557) | Cod sursa (job #1160845)
#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']) {
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 - 1] - 'a'] = 0;
st.push (node);
}
}
int find () {
int node, i;
node = 1;
i = 0;
while (i < l && node) {
node = trie [node].sons [s [i] - 'a'];
++ i;
}
return node;
}
int query () {
int node = 1, i = 0;
while (i < l && node) {
node = trie [node].sons [s [i] - 'a'];
i ++;
}
if (i == l && node)
return i;
else return i - 1;
}
int main () {
int type, node, line = 0;
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);
line ++;
}
else {printf ("0\n");line ++;}
}
else
{printf ("%d\n", query ());line ++;}
}
return 0;
}