#include <bits/stdc++.h>
using namespace std;
const int N = 500005;
int n, m;
namespace U {
int fa[N * 2], cnt[N * 2];
long long w[N * 2], sum[N * 2];
void Init() {
  for (int i = 1; i <= n; ++i) {
    fa[i] = i;
    cnt[i] = 1;
  }
  return;
}
int Gf(int k) {
  if (fa[k] == k) return k;
  int g = Gf(fa[k]);
  sum[k] += sum[fa[k]];
  return fa[k] = g;
}
void U(int x, int y, int t) {
  x = Gf(x);
  y = Gf(y);
  if (x == y) throw;
  cnt[n + t] = cnt[x] + cnt[y];
  fa[x] = fa[y] = fa[n + t] = n + t;
  sum[x] += w[x];
  sum[y] += w[y];
  return;
}
void A(int x) {
  x = Gf(x);
  w[x] += cnt[x];
  return;
}
long long Q(int x) {
  Gf(x);
  return sum[x] + w[fa[x]];
}
}  // namespace U
namespace M {
int fa[N * 2], lst[N * 2];
void Init() {
  for (int i = 1; i <= n; ++i) fa[i] = i;
  return;
}
int Gf(int k) {
  if (fa[k] == k) return k;
  int g = Gf(fa[k]);
  lst[k] = max(lst[k], lst[fa[k]]);
  return fa[k] = g;
}
void M(int x, int y, int t) {
  x = Gf(x);
  y = Gf(y);
  if (x == y) throw;
  fa[x] = fa[y] = fa[n + t] = n + t;
  return;
}
void Z(int x, int t) {
  lst[Gf(x)] = t;
  return;
}
int Q(int x) {
  Gf(x);
  return lst[x];
}
}  // namespace M
int q[N];
long long res[N];
vector<int> v[N];
int main() {
  scanf("%d%d", &n, &m);
  memset(res, -1, sizeof(res));
  M::Init();
  for (int i = 1; i <= m; ++i) {
    char ch[10];
    scanf("%s", ch);
    if (ch[0] == 'U') {
      int x, y;
      scanf("%d%d", &x, &y);
    } else if (ch[0] == 'M') {
      int x, y;
      scanf("%d%d", &x, &y);
      M::M(x, y, i);
    } else if (ch[0] == 'A') {
      int x;
      scanf("%d", &x);
    } else if (ch[0] == 'Z') {
      int x;
      scanf("%d", &x);
      M::Z(x, i);
    } else if (ch[0] == 'Q') {
      int x;
      scanf("%d", &x);
      res[i] = 0;
      q[i] = x;
      v[M::Q(x)].push_back(i);
    } else
      throw;
  }
  rewind(stdin);
  scanf("%*d%*d");
  U::Init();
  for (int i = 1; i <= m; ++i) {
    char ch[10];
    scanf("%s", ch);
    if (ch[0] == 'U') {
      int x, y;
      scanf("%d%d", &x, &y);
      U::U(x, y, i);
    } else if (ch[0] == 'M') {
      int x, y;
      scanf("%d%d", &x, &y);
    } else if (ch[0] == 'A') {
      int x;
      scanf("%d", &x);
      U::A(x);
    } else if (ch[0] == 'Z') {
      int x;
      scanf("%d", &x);
    } else if (ch[0] == 'Q') {
      int x;
      scanf("%d", &x);
      res[i] += U::Q(x);
    } else
      throw;
    for (int x : v[i]) res[x] -= U::Q(q[x]);
  }
  for (int i = 1; i <= m; ++i)
    if (res[i] >= 0) printf("%lld\n", res[i]);
  return 0;
}
