#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 500;
int ch[N][2], n, m, size[N];
long long ans[N];
struct DSU {
  int t[N], fa[N], node_cnt;
  void clear() {
    for (int i = 1; i <= n * 2; i++) fa[i] = i;
    for (int i = 1; i <= n; i++) size[i] = 1;
    node_cnt = n;
  }
  int find(int x) {
    if (x == fa[x]) return x;
    int tfa = find(fa[x]);
    t[x] = max(t[x], t[fa[x]]);
    fa[x] = tfa;
    return tfa;
  }
  void merge(int u, int v, int f) {
    u = find(u), v = find(v);
    if (u == v) return;
    ++node_cnt;
    fa[u] = fa[v] = node_cnt;
    if (f)
      ch[node_cnt][0] = u, ch[node_cnt][1] = v,
      size[node_cnt] = size[u] + size[v];
  }
} bcj2, bcj1;
struct Q {
  int l, r, id;
};
long long a[N];
void update(int x, int w) {
  for (; x <= m; x += x & -x) a[x] += w;
}
long long query(int x) {
  long long ans = 0;
  for (; x; x -= x & -x) ans += a[x];
  return ans;
}
vector<int> add[N];
vector<Q> q[N];
void dfs(int u) {
  for (vector<int>::iterator it = add[u].begin(); it != add[u].end(); ++it)
    update(*it, size[u]);
  for (vector<Q>::iterator it = q[u].begin(); it != q[u].end(); ++it)
    ans[it->id] = query(it->r) - query(it->l);
  if (ch[u][0]) dfs(ch[u][0]), dfs(ch[u][1]);
  for (vector<int>::iterator it = add[u].begin(); it != add[u].end(); ++it)
    update(*it, -size[u]);
}
int main() {
  scanf("%d%d", &n, &m);
  bcj1.clear(), bcj2.clear();
  int qn = 0;
  for (int i = 1, x, y; i <= m; i++) {
    char st[5];
    scanf("%s", st + 1);
    scanf("%d", &x);
    if (st[1] == 'U' || st[1] == 'M') scanf("%d", &y);
    switch (st[1]) {
      case 'U':
        bcj1.merge(x, y, 1);
        break;
      case 'M':
        bcj2.merge(x, y, 0);
        break;
      case 'A':
        add[bcj1.find(x)].push_back(i);
        break;
      case 'Z': {
        int u = bcj2.find(x);
        bcj2.t[u] = i;
        break;
      }
      case 'Q': {
        bcj2.find(x);
        q[x].push_back((Q){bcj2.t[x], i, ++qn});
      }
    }
  }
  for (int i = bcj1.node_cnt; i >= 1; i--)
    if (bcj1.fa[i] == i) dfs(i);
  for (int i = 1; i <= qn; i++) printf("%lld\n", ans[i]);
}
