#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
struct assign_dsu {
  int fa[1000005], v[1000005], id[1000005];
  int n;
  void init(int n) {
    this->n = n;
    for (int i = 1; i <= n; i++) fa[i] = id[i] = i;
  }
  int getf(int x) {
    if (fa[x] == x) return x;
    int t = getf(fa[x]);
    v[x] = max(v[x], v[fa[x]]);
    return fa[x] = t;
  }
  void mer(int s1, int s2) {
    int x = id[s1], y = id[s2];
    fa[x] = fa[y] = ++n;
    fa[n] = n;
    id[s1] = n;
  }
  void set(int s, int to) { v[id[s]] = to; }
  int query(int x) {
    getf(x);
    return v[x];
  }
} f1;
struct add_dsu {
  int fa[1000005], sz[1000005], id[1000005];
  long long v[1000005];
  int n;
  void init(int n) {
    this->n = n;
    for (int i = 1; i <= n; i++) {
      fa[i] = id[i] = i;
      sz[i] = 1;
    }
  }
  int getf(int x) {
    if (fa[x] == x) return x;
    int t = getf(fa[x]);
    if (t != fa[x]) v[x] += v[fa[x]];
    return fa[x] = t;
  }
  void mer(int s1, int s2) {
    int x = id[s1], y = id[s2];
    fa[x] = fa[y] = ++n;
    sz[n] = sz[x] + sz[y];
    fa[n] = n;
    id[s1] = n;
  }
  void add(int s, int to) { v[id[s]] += to; }
  int getsz(int s) { return sz[id[s]]; }
  long long query(int x) {
    int t = getf(x);
    return v[x] + (x == t ? 0 : v[t]);
  }
} f2;
struct query {
  int op, sgn, id, t, x, y;
  friend bool operator<(query a, query b) { return a.t < b.t; }
} q[1000005];
long long ans[1000005];
int main() {
  int n = read(), m = read(), cur = 0;
  f1.init(n);
  f2.init(n);
  memset(ans, -1, sizeof ans);
  for (int i = 1; i <= m; i++) {
    char c = getchar();
    if (c == 'M') {
      int x = read(), y = read();
      f1.mer(x, y);
    } else if (c == 'Z')
      f1.set(read(), i);
    else if (c == 'A')
      q[++cur] = (query){2, 0, 0, i, read()};
    else if (c == 'U') {
      int x = read(), y = read();
      q[++cur] = (query){1, 0, 0, i, x, y};
    } else {
      int x = read(), o = f1.query(x);
      ans[i] = 0;
      q[++cur] = (query){3, 1, i, i, x};
      if (o) q[++cur] = (query){3, -1, i, o, x};
    }
  }
  sort(q + 1, q + cur + 1);
  for (int i = 1; i <= cur; i++) {
    if (q[i].op == 1)
      f2.mer(q[i].x, q[i].y);
    else if (q[i].op == 2)
      f2.add(q[i].x, f2.getsz(q[i].x));
    else
      ans[q[i].id] += q[i].sgn * f2.query(q[i].x);
  }
  for (int i = 1; i <= m; i++)
    if (ans[i] != -1) printf("%I64d\n", ans[i]);
  return 0;
}
