#include <bits/stdc++.h>
using namespace std;
inline long long read() {
  long long k = 1, re = 0;
  char ch = getchar();
  while (ch > '9' || ch < '0') {
    if (ch == '-') k = -1;
    ch = getchar();
  }
  while (ch <= '9' && ch >= '0') {
    re = re * 10 + ch - 48;
    ch = getchar();
  }
  return re * k;
}
inline void write(long long x) {
  if (x < 0) return putchar('-'), write(-x), void();
  if (x <= 9) return putchar(x + 48), void();
  return write(x / 10), write(x % 10), void();
}
struct trie {
  long long ch[26], fa, cnt, ch2[26], sum;
} e[300005];
char s[300005];
long long rt[2][300005], tot, num[2], n, q;
long long head, tail, st[300005], g[2][300005];
inline void build_trie(long long x, long long z) {
  rt[z][x] = ++tot;
  long long u = tot;
  for (register long long i = 1; i <= n; i++) {
    if (!e[u].ch[s[i] - 'a']) e[u].ch[s[i] - 'a'] = ++tot;
    u = e[u].ch[s[i] - 'a'];
  }
  e[u].cnt++;
}
long long merge(long long u, long long v) {
  if (!u || !v) return u | v;
  e[u].cnt += e[v].cnt;
  for (register long long i = 0; i < 26; i++)
    e[u].ch[i] = merge(e[u].ch[i], e[v].ch[i]);
  return u;
}
inline void getfa(long long rt) {
  head = 1, tail = 0;
  for (register long long i = 0; i < 26; i++)
    if (e[rt].ch[i]) {
      e[rt].ch2[i] = e[rt].ch[i];
      e[e[rt].ch[i]].fa = rt;
      st[++tail] = e[rt].ch[i];
    } else
      e[rt].ch2[i] = rt;
  while (head <= tail) {
    long long x = st[head];
    for (register long long i = 0; i < 26; i++) {
      if (e[x].ch[i]) {
        e[x].ch2[i] = e[x].ch[i];
        e[e[x].ch[i]].fa = e[e[x].fa].ch2[i];
        st[++tail] = e[x].ch2[i];
      } else
        e[x].ch2[i] = e[e[x].fa].ch2[i];
    }
    e[x].sum = e[x].cnt + e[e[x].fa].sum;
    head++;
  }
}
inline void ins(long long z) {
  build_trie(++num[z], z);
  g[z][num[z]] = 1;
  while (g[z][num[z]] == g[z][num[z] - 1] && num[z] > 1) {
    num[z]--;
    g[z][num[z]] += g[z][num[z] + 1];
    rt[z][num[z]] = merge(rt[z][num[z]], rt[z][num[z] + 1]);
  }
  getfa(rt[z][num[z]]);
}
inline long long query(long long z) {
  long long ans = 0;
  for (register long long i = 1; i <= num[z]; i++) {
    long long u = rt[z][i];
    for (register long long j = 1; j <= n; j++) {
      u = e[u].ch2[s[j] - 'a'];
      ans += e[u].sum;
    }
  }
  return ans;
}
signed main() {
  q = read();
  while (q--) {
    long long typ = read();
    scanf("%s", s + 1);
    n = strlen(s + 1);
    if (typ == 1 || typ == 2) ins(typ - 1);
    if (typ == 3) write(query(0) - query(1)), puts("");
    fflush(stdout);
  }
  return 0;
}
