#include <bits/stdc++.h>
using namespace std;
const int NS = 26;
const int NB = 30;
struct StringTrie {
  StringTrie *child[NS];
  int dat;
  StringTrie() {
    for (int i = 0, _n = (NS); i < _n; i++) child[i] = NULL;
    dat = -1;
  }
  StringTrie(StringTrie *node) {
    for (int i = 0, _n = (NS); i < _n; i++) child[i] = node->child[i];
    dat = node->dat;
  }
  StringTrie *set(string &s, int val, int pos = 0) {
    StringTrie *node = new StringTrie(this);
    if (pos >= s.size()) {
      node->dat = val;
    } else {
      int v = s[pos] - 'a';
      if (!child[v]) child[v] = new StringTrie();
      node->child[v] = child[v]->set(s, val, pos + 1);
    }
    return node;
  }
  int get(string &s, int pos = 0) {
    if (pos >= s.size()) return dat;
    int v = s[pos] - 'a';
    if (!child[v]) return -1;
    return child[v]->get(s, pos + 1);
  }
};
struct BinaryTrie {
  BinaryTrie *child[2];
  int dat;
  BinaryTrie() {
    child[0] = child[1] = NULL;
    dat = 0;
  }
  BinaryTrie(BinaryTrie *node) {
    child[0] = node->child[0];
    child[1] = node->child[1];
    dat = node->dat;
  }
  BinaryTrie *add(int a, int val, int pos = NB) {
    BinaryTrie *node = new BinaryTrie(this);
    node->dat += val;
    if (pos >= 0) {
      int v = (a >> pos) & 1;
      if (!child[v]) child[v] = new BinaryTrie();
      node->child[v] = child[v]->add(a, val, pos - 1);
    }
    return node;
  }
  int get(int a, int pos = NB) {
    if (pos < 0) return 0;
    int v = (a >> pos) & 1;
    int res = 0;
    if (v) {
      if (child[0]) res += child[0]->dat;
      if (child[1]) res += child[1]->get(a, pos - 1);
    } else {
      if (child[0]) res += child[0]->get(a, pos - 1);
    }
    return res;
  }
};
StringTrie **st;
BinaryTrie **bt;
void solve() {
  int q, prior, num;
  cin >> q;
  st = new StringTrie *[100111];
  bt = new BinaryTrie *[100111];
  st[0] = new StringTrie();
  bt[0] = new BinaryTrie();
  string operation, word;
  for (int i = (1), _b = (q); i <= _b; i++) {
    cin >> operation;
    if (operation == "set") {
      cin >> word >> prior;
      num = st[i - 1]->get(word);
      st[i] = st[i - 1]->set(word, prior);
      if (num >= 0) {
        bt[i] = bt[i - 1]->add(num, -1);
        bt[i] = bt[i]->add(prior, 1);
      } else {
        bt[i] = bt[i - 1]->add(prior, 1);
      }
    } else if (operation == "remove") {
      cin >> word;
      num = st[i - 1]->get(word);
      st[i] = st[i - 1]->set(word, -1);
      if (num >= 0) {
        bt[i] = bt[i - 1]->add(num, -1);
      } else {
        bt[i] = bt[i - 1];
      }
    } else if (operation == "undo") {
      cin >> num;
      st[i] = st[i - num - 1];
      bt[i] = bt[i - num - 1];
    } else {
      cin >> word;
      st[i] = st[i - 1];
      bt[i] = bt[i - 1];
      prior = st[i]->get(word);
      if (prior >= 0) {
        cout << bt[i]->get(prior) << endl;
      } else {
        cout << -1 << endl;
      }
    }
  }
}
int main() {
  solve();
  return 0;
}
