#include <bits/stdc++.h>
using namespace std;
const long long N = 5e5 + 10;
struct Q {
  long long x, qu, id;
};
vector<Q> g[N];
long long n, m, qid, ans[N], px[N], py[N];
char opt[N][2];
long long fa[N], va[N];
inline void Pre() {
  memset(va, 0, (n + 1) * sizeof *va);
  memset(fa, -1, (n + 1) * sizeof *fa);
}
inline long long Ask(long long x) {
  while (fa[x] > 0) x = fa[x];
  return x;
}
inline void Merge(long long u, long long v) {
  u = Ask(u);
  v = Ask(v);
  if (u == v) return;
  if (-fa[u] < -fa[v]) swap(u, v);
  fa[u] += fa[v];
  fa[v] = u;
  va[v] -= va[u];
}
list<long long> tg[N];
signed main() {
  scanf("%lld%lld", &n, &m);
  Pre();
  for (long long i = 1; i <= m; ++i) {
    scanf("%s%lld", opt[i], px + i);
    if (opt[i][0] == 'M' || opt[i][0] == 'U') scanf("%lld", py + i);
    if (opt[i][0] == 'M') {
      tg[px[i]].splice(tg[px[i]].begin(), tg[py[i]]);
      tg[px[i]].push_back(py[i]);
    } else if (opt[i][0] == 'Z') {
      for (__typeof(tg[px[i]].begin()) it = tg[px[i]].begin();
           it != tg[px[i]].end(); ++it)
        Merge(px[i], *it);
      tg[px[i]].clear();
      va[Ask(px[i])] = i;
    } else if (opt[i][0] == 'Q') {
      long long ladel = va[Ask(px[i])];
      g[i].push_back((Q){px[i], 1, ++qid});
      if (ladel) g[ladel].push_back((Q){px[i], -1, qid});
    }
  }
  Pre();
  for (long long i = 1; i <= m; ++i) {
    if (opt[i][0] == 'A') {
      long long u = Ask(px[i]);
      va[u] -= fa[u];
    } else if (opt[i][0] == 'U') {
      Merge(px[i], py[i]);
    }
    for (__typeof(g[i].begin()) it = g[i].begin(); it != g[i].end(); ++it) {
      long long sm = 0, x = it->x;
      while (1) {
        sm += va[x];
        if (fa[x] < 0) break;
        x = fa[x];
      }
      ans[it->id] += it->qu * sm;
    }
  }
  for (long long i = 1; i <= qid; ++i) printf("%lld\n", ans[i]);
  return 0;
}
