#include <bits/stdc++.h>
using namespace std;
struct Query1 {
  long long type, x, y;
} A[500500];
long long n, m, b[500500];
struct Query2 {
  long long id, x, time, k;
  bool operator<(const Query2 &p) const { return time < p.time; }
} B[500500];
long long Bcnt, anscnt;
long long ans[500500];
struct Union_set1 {
  long long tot;
  long long fa[500500 << 1], val[500500 << 1];
  inline long long find(long long x) {
    if (fa[x] == x) return x;
    long long res = find(fa[x]);
    val[x] = max(val[x], val[fa[x]]);
    fa[x] = res;
    return res;
  }
  inline long long Union(long long x, long long y) {
    tot++;
    return fa[tot] = fa[x] = fa[y] = tot;
  }
  inline long long getval(long long x) {
    find(x);
    return val[x];
  }
} s1;
struct Union_set2 {
  long long tot;
  long long v[500500 << 1], V[500500 << 1], fa[500500 << 1], size[500500];
  inline long long find(long long x) {
    if (fa[x] == x) return x;
    long long res = find(fa[x]);
    v[x] += v[fa[x]];
    fa[x] = res;
    return res;
  }
  inline long long Union(long long x, long long y) {
    tot++;
    fa[x] = fa[y] = fa[tot] = tot;
    v[x] = V[x];
    V[x] = 0;
    v[y] = V[y];
    V[y] = 0;
    size[tot] = size[x] + size[y];
    return tot;
  }
  inline long long getval(long long x) {
    long long t = find(x);
    return v[x] + V[t];
  }
} s2;
signed main() {
  scanf("%lld%lld", &n, &m);
  s1.tot = s2.tot = n;
  for (long long i = 1; i <= n; i++) s1.fa[i] = s2.fa[i] = i, s2.size[i] = 1;
  for (long long i = 1; i <= m; i++) {
    char c;
    cin >> c;
    if (c == 'U' || c == 'M')
      scanf("%lld%lld", &A[i].x, &A[i].y);
    else
      scanf("%lld", &A[i].x);
    if (c == 'U') A[i].type = 1;
    if (c == 'M') A[i].type = 2;
    if (c == 'A') A[i].type = 3;
    if (c == 'Z') A[i].type = 4;
    if (c == 'Q') A[i].type = 5;
  }
  for (long long i = 1; i <= n; i++) b[i] = i;
  for (long long i = 1; i <= m; i++) {
    if (A[i].type == 2) b[A[i].x] = s1.Union(b[A[i].x], b[A[i].y]);
    if (A[i].type == 4) s1.val[b[A[i].x]] = i;
    if (A[i].type == 5) {
      anscnt++;
      Bcnt++;
      B[Bcnt].id = anscnt;
      B[Bcnt].x = A[i].x;
      B[Bcnt].time = s1.getval(A[i].x);
      B[Bcnt].k = -1;
      Bcnt++;
      B[Bcnt].id = anscnt;
      B[Bcnt].x = A[i].x;
      B[Bcnt].time = i;
      B[Bcnt].k = 1;
    }
  }
  sort(B + 1, B + Bcnt + 1);
  long long cur = 0;
  for (long long i = 1; i <= n; i++) b[i] = i;
  for (long long i = 0; i <= m; i++) {
    if (A[i].type == 1) b[A[i].x] = s2.Union(b[A[i].x], b[A[i].y]);
    if (A[i].type == 3) s2.V[b[A[i].x]] += s2.size[b[A[i].x]];
    while (cur + 1 <= Bcnt && B[cur + 1].time <= i) {
      cur++;
      ans[B[cur].id] += s2.getval(B[cur].x) * B[cur].k;
    }
  }
  for (long long i = 1; i <= anscnt; i++) printf("%lld\n", ans[i]);
}
