#include <bits/stdc++.h>
using namespace std;
struct trie {
  int val;
  trie *chi[28];
  trie() {
    for (int i = 0; i < 28; i++) {
      chi[i] = nullptr;
    }
    val = -1;
  }
  trie(trie *cpy) {
    for (int i = 0; i < 28; i++) {
      chi[i] = cpy->chi[i];
    }
    val = cpy->val;
  }
  void add(string &str, int k) {
    trie *cur = this;
    int n = str.size();
    for (int i = 0; i < n; i++) {
      int v = str[i] - 'a';
      if (!cur->chi[v]) {
        cur->chi[v] = new trie();
      } else {
        cur->chi[v] = new trie(cur->chi[v]);
      }
      cur = cur->chi[v];
    }
    cur->val = k;
  }
  int get(string &str) {
    int n = str.size();
    trie *cur = this;
    for (int i = 0; i < n; i++) {
      int v = str[i] - 'a';
      if (!cur->chi[v]) {
        return -1;
      }
      cur = cur->chi[v];
    }
    return cur->val;
  }
};
struct btrie {
  int val;
  btrie *chi[2];
  btrie() {
    chi[0] = nullptr;
    chi[1] = nullptr;
    val = 0;
  }
  btrie(btrie *cpy) {
    chi[0] = cpy->chi[0];
    chi[1] = cpy->chi[1];
    val = cpy->val;
  }
  void add(int k, int p) {
    btrie *cur = this;
    for (int pos = 30; pos >= 0; pos--) {
      int v = (k >> pos) & 1;
      if (!cur->chi[v]) {
        cur->chi[v] = new btrie();
      } else {
        cur->chi[v] = new btrie(cur->chi[v]);
      }
      cur->val += p;
      cur = cur->chi[v];
    }
    cur->val += p;
  }
  int calc(int k) {
    int ans = 0;
    btrie *cur = this;
    for (int pos = 30; pos >= 0; pos--) {
      int v = (k >> pos) & 1;
      int l = 0, r = 0;
      if (cur->chi[0]) l = cur->chi[0]->val;
      if (cur->chi[1]) r = cur->chi[1]->val;
      if (v) {
        ans += l;
      }
      cur = cur->chi[v];
    }
    return ans;
  }
};
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int q;
  cin >> q;
  vector<trie *> s(q + 2, nullptr);
  vector<btrie *> t(q + 2, nullptr);
  s[0] = new trie();
  t[0] = new btrie();
  for (int i = 1; i <= q; i++) {
    string a, b;
    cin >> a;
    int p;
    if (a[0] == 's') {
      cin >> b >> p;
      int temp = s[i - 1]->get(b);
      s[i] = new trie(s[i - 1]);
      s[i]->add(b, p);
      t[i] = new btrie(t[i - 1]);
      if (temp == -1) {
        t[i]->add(p, 1);
      } else {
        t[i]->add(temp, -1);
        t[i]->add(p, 1);
      }
    } else if (a[0] == 'q') {
      cin >> b;
      s[i] = s[i - 1];
      t[i] = t[i - 1];
      int temp = s[i]->get(b);
      if (temp == -1) {
        cout << -1 << '\n';
      } else {
        cout << t[i]->calc(temp) << '\n';
      }
      cout << flush;
    } else if (a[0] == 'r') {
      cin >> b;
      int temp = s[i - 1]->get(b);
      s[i] = new trie(s[i - 1]);
      s[i]->add(b, -1);
      if (temp == -1) {
        t[i] = t[i - 1];
      } else {
        t[i] = new btrie(t[i - 1]);
        t[i]->add(temp, -1);
      }
    } else {
      cin >> p;
      s[i] = s[i - p - 1];
      t[i] = t[i - p - 1];
    }
  }
  return 0;
}
