#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10, M = 1e6 + 5, INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
int rt1[N * 100], rt2[N * 100], sum[N * 100], ls[N * 100], rs[N * 100], cnt;
void modify(int &now, int pre, int l, int r, int pos, int val) {
  now = ++cnt;
  ls[now] = ls[pre], rs[now] = rs[pre], sum[now] = sum[pre] + val;
  if (l == r) return;
  int mid = (l + r) >> 1;
  if (pos <= mid)
    modify(ls[now], ls[pre], l, mid, pos, val);
  else
    modify(rs[now], rs[pre], mid + 1, r, pos, val);
}
int query(int now, int l, int r, int ql, int qr) {
  if (ql <= l && qr >= r) return sum[now];
  int mid = (l + r) >> 1;
  int ans = 0;
  if (ql <= mid) ans += query(ls[now], l, mid, ql, qr);
  if (qr > mid) ans += query(rs[now], mid + 1, r, ql, qr);
  return ans;
}
map<string, int> id;
int tot;
int getid(string s) {
  if (id.find(s) == id.end()) {
    id[s] = ++tot;
    return tot;
  } else
    return id[s];
}
void solve() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    string opt, name;
    int priority;
    cin >> opt;
    rt1[i] = rt1[i - 1], rt2[i] = rt2[i - 1];
    if (opt == "set") {
      cin >> name >> priority;
      int x = getid(name);
      int pre = query(rt2[i], 1, MOD, x, x);
      if (!pre) {
        modify(rt2[i], rt2[i], 1, MOD, x, priority);
        modify(rt1[i], rt1[i], 1, MOD, priority, 1);
      } else {
        modify(rt2[i], rt2[i], 1, MOD, x, -pre + priority);
        modify(rt1[i], rt1[i], 1, MOD, pre, -1);
        modify(rt1[i], rt1[i], 1, MOD, priority, 1);
      }
    } else if (opt == "query") {
      cin >> name;
      int x = getid(name);
      priority = query(rt2[i], 1, MOD, x, x);
      if (!priority)
        cout << -1 << endl;
      else if (priority == 1)
        cout << 0 << endl;
      else
        cout << query(rt1[i], 1, MOD, 1, priority - 1) << endl;
      fflush(stdout);
    } else if (opt == "remove") {
      cin >> name;
      int x = getid(name);
      priority = query(rt2[i], 1, MOD, x, x);
      if (!priority) continue;
      modify(rt2[i], rt2[i], 1, MOD, x, -priority);
      modify(rt1[i], rt1[i], 1, MOD, priority, -1);
    } else if (opt == "undo") {
      int x;
      cin >> x;
      rt1[i] = rt1[i - x - 1], rt2[i] = rt2[i - x - 1];
    }
  }
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  solve();
  return 0;
}
