#include <bits/stdc++.h>
using namespace std;
const int inf = 1000000000;
const int MOD = 1000000007;
const int N = 500009;
int u[N + 1], v[N + 1];
vector<int> uall[N + 1], mall[N + 1];
vector<int> zero[N + 1];
long long add_each[N + 1], add1[N + 1];
int o[N + 1];
int ID[N + 1];
int last[N + 1];
int get(int *a, int v) {
  if (a[v] == v) return v;
  return a[v] = get(a, a[v]);
}
int main() {
  int n, m;
  scanf("%d %d\n", &n, &m);
  for (int i = (1); i <= (n); ++i) {
    u[i] = i;
    uall[i].push_back(i);
    zero[i].push_back(i);
    o[i] = i;
    v[i] = i;
  }
  while (m--) {
    char mode;
    scanf("%c ", &mode);
    if (mode == 'U') {
      int a, b;
      scanf("%d %d\n", &a, &b);
      a = get(u, a);
      b = get(u, b);
      if ((int)((uall[a]).size()) < (int)((uall[b]).size())) swap(a, b);
      u[b] = a;
      for (int i = (0); i <= ((int)((uall[b]).size()) - 1); ++i) {
        int x = uall[b][i];
        uall[a].push_back(x);
        add1[x] = add1[x] + add_each[b] - add_each[a];
      }
      uall[b].clear();
      for (int i = (0); i <= ((int)((zero[b]).size()) - 1); ++i) {
        int x = zero[b][i];
        zero[a].push_back(x);
      }
      zero[b].clear();
    } else if (mode == 'M') {
      int a, b;
      scanf("%d %d\n", &a, &b);
      a = get(v, a);
      b = get(v, b);
      if ((int)((mall[a]).size()) < (int)((mall[b]).size())) swap(a, b);
      v[b] = a;
      for (int i = (0); i <= ((int)((mall[b]).size()) - 1); ++i) {
        int x = mall[b][i];
        mall[a].push_back(x);
      }
      mall[b].clear();
    } else if (mode == 'A') {
      int a;
      scanf("%d\n", &a);
      a = get(u, a);
      for (int i = (0); i <= ((int)((zero[a]).size()) - 1); ++i) {
        int x = zero[a][i];
        add1[x] = -add_each[a];
        mall[get(v, x)].push_back(x);
      }
      zero[a].clear();
      add_each[a] += (int)((uall[a]).size());
    } else if (mode == 'Z') {
      int a;
      scanf("%d\n", &a);
      a = get(v, a);
      for (int i = (0); i <= ((int)((mall[a]).size()) - 1); ++i) {
        int x = mall[a][i];
        int bu = get(u, x);
        if (ID[bu] == m)
          o[x] = last[bu];
        else {
          add1[x] = -add_each[bu];
          last[bu] = x;
          zero[bu].push_back(x);
          ID[bu] = m;
        }
      }
      mall[a].clear();
    } else if (mode == 'Q') {
      int a;
      scanf("%d\n", &a);
      a = get(o, a);
      long long ans = add1[a] + add_each[get(u, a)];
      printf("%I64d\n", ans);
    }
  }
}
