#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
const int maxm = 1e7 + 5;
const int INF = 1e9;
long long gcd(long long x, long long y) { return y ? gcd(y, x % y) : x; }
string s;
int n, x;
int rt1[maxn], rt2[maxn];
int ls[maxm], rs[maxm], sum[maxm];
int id = 0, tot = 0;
map<string, int> mp;
int query(int o, int l, int r, int pl, int pr) {
  if (pl > pr) return 0;
  if (pl <= l && r <= pr) return sum[o];
  int mid = l + r >> 1, ans = 0;
  if (pl <= mid) ans += query(ls[o], l, mid, pl, pr);
  if (mid < pr) ans += query(rs[o], mid + 1, r, pl, pr);
  return ans;
}
void update(int &o, int last, int l, int r, int p, int v) {
  o = ++tot;
  ls[o] = ls[last], rs[o] = rs[last];
  sum[o] = sum[last] + v;
  if (l == r) return;
  int mid = l + r >> 1;
  if (p <= mid)
    update(ls[o], ls[last], l, mid, p, v);
  else
    update(rs[o], rs[last], mid + 1, r, p, v);
}
int getid(string p) {
  if (mp.count(p))
    return mp[p];
  else
    return mp[p] = ++id;
}
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) {
    rt1[i] = rt1[i - 1], rt2[i] = rt2[i - 1];
    cin >> s;
    if (s[0] == 's') {
      cin >> s >> x;
      int idx = getid(s);
      int ret = query(rt2[i], 1, INF, idx, idx);
      if (ret) update(rt1[i], rt1[i], 1, INF, ret, -1);
      update(rt1[i], rt1[i], 1, INF, x, 1);
      update(rt2[i], rt2[i], 1, INF, idx, x - ret);
    } else if (s[0] == 'q') {
      cin >> s;
      int idx = getid(s);
      int ret = query(rt2[i], 1, INF, idx, idx);
      if (ret == 0)
        puts("-1");
      else
        printf("%d\n", query(rt1[i], 1, INF, 1, ret - 1));
      fflush(stdout);
    } else if (s[0] == 'u') {
      cin >> x;
      rt1[i] = rt1[i - x - 1];
      rt2[i] = rt2[i - x - 1];
    } else {
      cin >> s;
      int idx = getid(s);
      int ret = query(rt2[i], 1, INF, idx, idx);
      if (ret == 0) continue;
      update(rt1[i], rt1[i], 1, INF, ret, -1);
      update(rt2[i], rt2[i], 1, INF, idx, -ret);
    }
  }
}
