#include <bits/stdc++.h>
using namespace std;
bool solve(int);
int main() {
  int test = 0;
  while (solve(test++))
    ;
  return 0;
}
const int N = 1000 * 1000 + 5;
char t[N];
int a[N], b[N];
int lz[N], n, m;
long long ans[N];
vector<int> g[N];
int p[N], pos[N], ptr;
int r[N];
void place(int v) {
  pos[v] = ptr++;
  for (int i = 0; i < int(int(g[v].size())); ++i) place(g[v][i]);
  r[v] = ptr - 1;
}
long long ft[N];
void inc(int i, long long d) {
  for (; i < N; i |= i + 1) ft[i] += d;
}
long long get(int r) {
  long long s = 0;
  for (; r >= 0; r = (r & (r + 1)) - 1) s += ft[r];
  return s;
}
bool solve(int) {
  if (scanf("%d%d", &n, &m) != 2) return false;
  for (int i = 0; i < int(m); ++i) {
    char buf[3];
    scanf("%s %d", buf, &a[i]);
    t[i] = buf[0];
    a[i]--;
    if (t[i] == 'U' || t[i] == 'M') {
      scanf("%d", &b[i]);
      b[i]--;
    }
  }
  ptr = 0;
  for (int i = 0; i < int(n); ++i) p[i] = -1;
  for (int i = 0; i < int(m); ++i)
    if (t[i] == 'M') p[b[i]] = a[i], g[a[i]].push_back(b[i]);
  for (int i = 0; i < int(n); ++i)
    if (p[i] == -1) place(i);
  assert(ptr == n);
  set<pair<int, int> > s;
  for (int i = m - 1; i >= 0; --i) {
    if (t[i] == 'Q') {
      lz[i] = 0;
      s.insert(make_pair(pos[a[i]], i));
    }
    if (t[i] == 'Z') {
      int L = pos[a[i]], R = r[a[i]];
      while (true) {
        set<pair<int, int> >::iterator it = s.lower_bound(make_pair(L, -1));
        if (it == s.end() || it->first > R) break;
        lz[it->second] = i;
        s.erase(it);
      }
    }
    if (t[i] == 'M') {
      assert(r[a[i]] == r[b[i]]);
      r[a[i]] = pos[b[i]] - 1;
    }
  }
  vector<pair<int, int> > v;
  for (int i = 0; i < int(m); ++i)
    if (t[i] == 'Q') v.push_back(make_pair(lz[i], i));
  sort(v.begin(), v.end());
  int vp = 0;
  ptr = 0;
  for (int i = 0; i < int(n); ++i) p[i] = -1;
  for (int i = 0; i < int(n); ++i) g[i].clear();
  for (int i = 0; i < int(m); ++i)
    if (t[i] == 'U') p[b[i]] = a[i], g[a[i]].push_back(b[i]);
  for (int i = 0; i < int(n); ++i)
    if (p[i] == -1) place(i);
  assert(ptr == n);
  for (int i = 0; i < int(n); ++i) r[i] = pos[i];
  for (int i = 0; i < int(m); ++i) {
    while (vp < int(v.size()) && v[vp].first == i) {
      ans[v[vp].second] = get(pos[a[v[vp].second]]);
      vp++;
    }
    if (t[i] == 'U') {
      int f = a[i], s = b[i];
      assert(r[f] + 1 == pos[s]);
      r[f] = r[s];
    }
    if (t[i] == 'A') {
      int f = a[i];
      int sz = r[f] - pos[f] + 1;
      inc(pos[f], +sz);
      inc(r[f] + 1, -sz);
    }
    if (t[i] == 'Q') {
      ans[i] = get(pos[a[i]]) - ans[i];
    }
  }
  for (int i = 0; i < int(m); ++i)
    if (t[i] == 'Q') printf("%I64d\n", ans[i]);
  return true;
}
