#include <bits/stdc++.h>
using namespace std;
const int N = 500000 + 5;
int cnt, tot, n, s[N * 2], size[N * 2], fa[N * 2], tag1[N * 2], now[N];
char ch[N];
pair<int, int> da[N];
long long tag2[N * 2], ans[N];
vector<pair<int, int> > vec[N];
void newer() {
  tot = n;
  memset(tag1, 0, sizeof(tag1));
  memset(tag2, 0, sizeof(tag2));
  memset(size, 0, sizeof(size));
  for (int i = 1; i <= 2 * n; i++) fa[i] = i;
  for (int i = 1; i <= n; i++) now[i] = i, size[i] = 1;
}
int find(int x) {
  if (fa[x] != fa[fa[x]]) {
    int k = find(fa[x]);
    tag2[x] += tag2[fa[x]];
    tag1[x] = max(tag1[x], tag1[fa[x]]);
    fa[x] = k;
  }
  return fa[x];
}
int merge(int x, int y) {
  size[++tot] = size[x] + size[y];
  return fa[x] = fa[y] = tot;
}
long long query(int x) {
  find(x);
  if (fa[x] != x)
    return tag2[x] + tag2[fa[x]];
  else
    return tag2[x];
}
int main() {
  int m, t;
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= m; i++) {
    scanf(" %c%d", &ch[i], &da[i].first);
    if (ch[i] == 'U' || ch[i] == 'M') scanf("%d", &da[i].second);
    if (ch[i] == 'Q') da[i].second = ++cnt;
  }
  newer();
  for (int i = 1; i <= m; i++) {
    if (ch[i] == 'M')
      now[da[i].first] = merge(now[da[i].first], now[da[i].second]);
    if (ch[i] == 'Z') tag1[now[da[i].first]] = i;
    if (ch[i] == 'Q')
      vec[max(tag1[find(da[i].first)], tag1[da[i].first])].push_back(da[i]);
  }
  newer();
  for (int i = 1; i <= m; i++) {
    if (ch[i] == 'U')
      now[da[i].first] = merge(now[da[i].first], now[da[i].second]);
    if (ch[i] == 'A') tag2[now[da[i].first]] += size[now[da[i].first]];
    if (ch[i] == 'Q') ans[da[i].second] += query(da[i].first);
    for (int j = 0; j < vec[i].size(); j++)
      ans[vec[i][j].second] -= query(vec[i][j].first);
  }
  for (int i = 1; i <= cnt; i++) printf("%I64d\n", ans[i]);
  return 0;
}
