#include <bits/stdc++.h>
using namespace std;
inline int Read() {
  char c = getchar();
  int num = 0;
  while ('0' > c || c > '9') c = getchar();
  while ('0' <= c && c <= '9') num = num * 10 + c - '0', c = getchar();
  return (num);
}
int n, m;
struct Dsu {
  int N, fa[1000010], mx[1000010], sz[1000010];
  long long sum[1000010];
  void Mem() {
    N = n;
    for (int i = 1; i <= n; i++) sz[i] = 1, mx[i] = sum[i] = 0, fa[i] = i;
  }
  int Get(int x) {
    if (x == fa[x]) return (x);
    int ff = Get(fa[x]);
    mx[x] = max(mx[x], mx[fa[x]]);
    if (fa[x] != ff) sum[x] += sum[fa[x]];
    return (fa[x] = ff);
  }
  void Merge(int x, int y) {
    int fx = Get(x), fy = Get(y);
    fa[fx] = fa[fy] = ++N;
    fa[N] = N;
    sz[N] = sz[fx] + sz[fy];
  }
  void Chg1(int x, int i) {
    int fx = Get(x);
    mx[fx] = i;
  }
  void Chg2(int x) {
    int fx = Get(x);
    sum[fx] += sz[fx];
  }
  int Ask1(int x) {
    int fx = Get(x);
    return (mx[x]);
  }
  long long Ask2(int x) {
    int fx = Get(x);
    if (fx == x) return (sum[x]);
    return (sum[x] + sum[fx]);
  }
} dsu;
long long ans[1000010];
bool v[1000010];
struct Que {
  int x, op, id;
};
vector<Que> que[1000010];
int op[1000010][2];
int main() {
  n = Read(), m = Read();
  dsu.Mem();
  for (int i = 1; i <= m; i++) {
    char o = getchar();
    while ('A' > o || o > 'Z') o = getchar();
    if (o == 'U') op[i][0] = Read(), op[i][1] = Read();
    if (o == 'M') {
      int a = Read(), b = Read();
      dsu.Merge(a, b);
    }
    if (o == 'A') op[i][0] = Read();
    if (o == 'Z') {
      int x = Read();
      dsu.Chg1(x, i);
    }
    if (o == 'Q') {
      int x = Read();
      v[i] = 1;
      int lst = dsu.Ask1(x);
      que[i].push_back((Que){x, 1, i});
      que[lst].push_back((Que){x, 0, i});
    }
  }
  dsu.Mem();
  for (int o = 1; o <= m; o++) {
    if (op[o][0] && !op[o][1]) dsu.Chg2(op[o][0]);
    if (op[o][0] && op[o][1]) dsu.Merge(op[o][0], op[o][1]);
    for (int j = 0; j < que[o].size(); j++) {
      long long num = dsu.Ask2(que[o][j].x);
      if (que[o][j].op == 0)
        ans[que[o][j].id] -= num;
      else
        ans[que[o][j].id] += num;
    }
  }
  for (int i = 1; i <= m; i++)
    if (v[i]) printf("%I64d\n", ans[i]);
}
