#include <bits/stdc++.h>
using namespace std;
long long n, m, f[1000000], kk, de[1000000], tim[1000000], k, dd, ff[1000000],
    dee[1000000];
struct lsg {
  char c;
  long long x, y, z, k;
} a[1000000], b[1000000];
long long fa(long long x) {
  if (f[x] == x) return x;
  long long k = fa(f[x]);
  tim[x] = max(tim[x], tim[f[x]]);
  de[x] += de[f[x]];
  f[x] = k;
  return k;
}
bool pd(lsg x, lsg y) { return x.y < y.y; }
signed main() {
  ios::sync_with_stdio(false);
  cin >> n >> m;
  for (long long i = 1; i <= m; i++) {
    cin >> a[i].c >> a[i].x;
    if (a[i].c == 'U' || a[i].c == 'M') cin >> a[i].y;
  }
  for (long long i = 1; i <= n; i++) f[i] = i;
  kk = n;
  for (long long i = 1; i <= m; i++) {
    if (a[i].c == 'M') {
      long long xx = fa(a[i].x), yy = fa(a[i].y);
      ++kk;
      f[xx] = f[yy] = f[kk] = kk;
    }
    if (a[i].c == 'Z') tim[fa(a[i].x)] = i;
    if (a[i].c == 'Q') {
      b[k + 1].x = b[k + 2].x = a[i].x;
      k += 2;
      fa(a[i].x);
      b[k].y = tim[a[i].x];
      b[k - 1].y = i;
      b[k].z = -1;
      b[k - 1].z = 1;
      b[k - 1].k = b[k].k = k / 2;
    }
  }
  sort(b + 1, b + 1 + k, pd);
  dd = 1;
  for (long long i = 1; i <= n; i++) f[i] = i, dee[i] = 1;
  kk = n;
  for (long long i = 1; i <= m; i++) {
    while (b[dd].y < i && dd <= k) {
      fa(b[dd].x);
      ff[b[dd].k] += b[dd].z * de[b[dd].x];
      dd++;
    }
    if (a[i].c == 'U') {
      long long xx = fa(a[i].x), yy = fa(a[i].y);
      ++kk;
      f[kk] = f[xx] = f[yy] = kk;
      dee[kk] = dee[xx] + dee[yy];
    }
    if (a[i].c == 'A') {
      long long k = fa(a[i].x);
      ++kk;
      de[k] = dee[kk] = dee[k];
      f[k] = f[kk] = kk;
    }
  }
  while (dd <= k) {
    fa(b[dd].x);
    ff[b[dd].k] += b[dd].z * de[b[dd].x];
    dd++;
  }
  k /= 2;
  for (long long i = 1; i <= k; i++) cout << ff[i] << endl;
}
