#include <bits/stdc++.h>
using namespace std;
const int N = 100005, M = 1000000000;
int s[N * 32 * 2][2] = {0}, z[N * 32 * 2] = {0}, r[N] = {0}, tol = 0;
int s2[N * 16][26] = {0}, z2[N * 16] = {0}, r2[N] = {0}, tol2 = 0;
int query(int id, int p, int q, int x) {
  if (x == q) return z[id];
  int mid = (p + q) / 2;
  if (x <= mid) return query(s[id][0], p, mid, x);
  return z[s[id][0]] + query(s[id][1], mid + 1, q, x);
}
int newnode(int id) {
  int node = ++tol;
  s[node][0] = s[id][0];
  s[node][1] = s[id][1];
  z[node] = z[id];
  return node;
}
int add(int id, int p, int q, int x, int d = 1) {
  int mid = (p + q) / 2, node = newnode(id);
  z[node] += d;
  if (p == q) return node;
  if (x <= mid)
    s[node][0] = add(s[node][0], p, mid, x, d);
  else
    s[node][1] = add(s[node][1], mid + 1, q, x, d);
  return node;
}
int newnode2(int id) {
  int node = ++tol2;
  memcpy(s2[node], s2[id], sizeof(s2[node]));
  z2[node] = z2[id];
  return node;
}
int add2(int id, const char *a, int x) {
  int node = newnode2(id);
  int now = node, pre = 0;
  while (*a) {
    pre = now;
    now = s2[now][(*a) - 'a'];
    now = newnode2(now);
    s2[pre][(*a) - 'a'] = now;
    a++;
  }
  z2[now] = x;
  return node;
}
int query2(int id, const char *a) {
  int now = id;
  while (*a) {
    now = s2[now][(*a) - 'a'];
    a++;
  }
  return z2[now];
}
void solve() {
  int p = 0, ans = 0, Q = 0, i = 0, now = 0, x = 0;
  char a[256] = {0}, str[256] = {0};
  scanf("%d", &Q);
  for (i = 1; i <= Q; i++) {
    scanf("%s", str);
    if (str[0] == 's') {
      scanf("%s%d", a, &x);
      p = query2(r2[i - 1], a);
      if (p) {
        now = add(r[i - 1], 0, M, p, -1);
        r2[i] = add2(r2[i - 1], a, x);
        r[i] = add(now, 0, M, x);
      } else {
        r2[i] = add2(r2[i - 1], a, x);
        r[i] = add(r[i - 1], 0, M, x);
      }
    } else if (str[0] == 'r') {
      scanf("%s", a);
      p = query2(r2[i - 1], a);
      if (p) {
        r2[i] = add2(r2[i - 1], a, 0);
        r[i] = add(r[i - 1], 0, M, p, -1);
      } else {
        r2[i] = r2[i - 1];
        r[i] = r[i - 1];
      }
    } else if (str[0] == 'q') {
      scanf("%s", a);
      r[i] = r[i - 1];
      r2[i] = r2[i - 1];
      p = query2(r2[i], a);
      if (p == 0) {
        printf("%d\n", -1);
      } else {
        ans = query(r[i], 0, M, p - 1);
        printf("%d\n", ans);
      }
      fflush(stdout);
    } else {
      scanf("%d", &x);
      r[i] = r[i - x - 1];
      r2[i] = r2[i - x - 1];
    }
  }
}
int main() {
  int o = 1;
  while (o--) {
    solve();
  }
  return 0;
}
