#include <bits/stdc++.h>
using namespace std;
const int maxn = 7000000;
struct persist_segtree {
  struct Node {
    int lft, rgt;
    int num;
  } segs[maxn];
  int rt[maxn];
  int tot;
  void init() {
    tot = 0;
    memset(segs, 0, sizeof(segs));
  }
  inline int getnum(int rt) { return rt ? segs[rt].num : 0; }
  void add(int &rt, int lft, int rgt, int pos, int num) {
    int nrt = ++tot;
    segs[nrt] = segs[rt];
    rt = nrt;
    int mid = (lft + rgt) / 2;
    if (lft == rgt) {
      segs[rt].num += num;
      return;
    }
    if (pos <= mid)
      add(segs[rt].lft, lft, mid, pos, num);
    else
      add(segs[rt].rgt, mid + 1, rgt, pos, num);
    segs[rt].num = getnum(segs[rt].lft) + getnum(segs[rt].rgt);
  }
  int query(int rt, int lft, int rgt, int beg, int end) {
    if (!rt) return 0;
    if (beg <= lft && rgt <= end) return segs[rt].num;
    if (beg > rgt || end < lft) return 0;
    int mid = (lft + rgt) / 2;
    return query(segs[rt].lft, lft, mid, beg, end) +
           query(segs[rt].rgt, mid + 1, rgt, beg, end);
  }
} tree1, tree2;
int tme = 0, q, id, nowp, prep;
string sname;
char ops[25], name[25];
map<string, int> mp;
int main() {
  tree1.init();
  tree2.init();
  scanf("%d", &q);
  for (int t = 1; t <= q; ++t) {
    tree1.rt[t] = tree1.rt[t - 1];
    tree2.rt[t] = tree2.rt[t - 1];
    scanf(" %s", ops);
    sname = string(name);
    if (ops[0] == 's') {
      int f = 1;
      scanf("%s%d", name, &nowp);
      sname = string(name);
      if (!mp.count(sname)) mp[sname] = mp.size() + 1, f = 0;
      id = mp[sname];
      prep = 0;
      prep = tree2.query(tree2.rt[t], 1, 1000000000, id, id);
      if (f && prep) tree1.add(tree1.rt[t], 1, 1000000000, prep, -1);
      tree1.add(tree1.rt[t], 1, 1000000000, nowp, 1);
      tree2.add(tree2.rt[t], 1, 1000000000, id, nowp - prep);
    } else if (ops[0] == 'q') {
      scanf("%s", name);
      sname = string(name);
      if (!mp.count(sname)) {
        printf("%d\n", -1);
        fflush(stdout);
        continue;
      }
      id = mp[sname];
      int prep = tree2.query(tree2.rt[t], 1, 1000000000, id, id);
      if (prep == 0) {
        puts("-1");
        fflush(stdout);
        continue;
      }
      int ans = tree1.query(tree1.rt[t], 1, 1000000000, 1, prep - 1);
      printf("%d\n", ans);
      fflush(stdout);
    } else if (ops[0] == 'u') {
      scanf("%d", &tme);
      tree1.rt[t] = tree1.rt[t - 1 - tme];
      tree2.rt[t] = tree2.rt[t - 1 - tme];
    } else if (ops[0] == 'r') {
      scanf("%s", name);
      sname = string(name);
      if (!mp.count(sname)) continue;
      id = mp[sname];
      int prep = tree2.query(tree2.rt[t], 1, 1000000000, id, id);
      if (!prep) continue;
      tree1.add(tree1.rt[t], 1, 1000000000, prep, -1);
      tree2.add(tree2.rt[t], 1, 1000000000, id, -prep);
    }
  }
  return 0;
}
