#include <bits/stdc++.h>
const int N = 5e5 + 5;
int n, m, a[N];
long long ans;
std::vector<std::pair<int, long long> > g[N];
struct DSU {
  int ff[N], sz[N], t[N];
  inline void init() {
    for (int i = 1; i <= n; i++) ff[i] = i, sz[i] = 1;
  }
  inline int find(int x) { return x == ff[x] ? x : find(ff[x]); }
  inline void merge(int x, int y, int v) {
    x = find(x), y = find(y);
    if (sz[x] < sz[y]) std::swap(x, y);
    ff[y] = x, sz[x] += sz[y], t[y] = v;
  }
} A, B;
inline int get(int x, std::pair<int, long long> v) {
  int l = 0, r = g[x].size() - 1, mid, y = r + 1;
  while (l <= r)
    g[x][mid = l + r >> 1] >= v ? (r = mid - 1, y = mid) : (l = mid + 1);
  return y;
}
int main() {
  scanf("%d%d", &n, &m), A.init(), B.init();
  int i, x, y, l, r;
  char o[2];
  for (i = 1; i <= n; i++) g[i].push_back(std::make_pair(-1, 0));
  for (i = 1; i <= m; i++) {
    scanf("%s%d", o, &x);
    if (o[0] == 'U') scanf("%d", &y), A.merge(x, y, i);
    if (o[0] == 'M') scanf("%d", &y), B.merge(x, y, i);
    if (o[0] == 'A')
      l = A.find(x),
      g[l].push_back(std::make_pair(i, A.sz[l] + g[l].back().second));
    if (o[0] == 'Z') a[B.find(x)] = i;
    if (o[0] == 'Q') {
      for (l = x, r = a[x]; B.ff[l] != l; l = B.ff[l])
        if (B.t[l] < a[B.ff[l]]) r = std::max(r, a[B.ff[l]]);
      for (l = x, ans = g[x].back().second -
                        g[x][get(x, std::make_pair(r, 0)) - 1].second;
           A.ff[l] != l; l = A.ff[l])
        ans +=
            g[A.ff[l]].back().second -
            g[A.ff[l]][get(A.ff[l], std::make_pair(std::max(r, A.t[l]), 0)) - 1]
                .second;
      printf("%lld\n", ans);
    }
  }
  return 0;
}
