#include <bits/stdc++.h>
using namespace std;
struct univer {
  int par, cnt, lef, h;
  vector<pair<int, long long> > ar;
};
struct voencom {
  int par, last, time, h;
};
struct obshag {
  int un, voen, last;
};
const int LEN = 500500;
int n, m, a, b;
char ch;
univer un[LEN];
voencom voen[LEN];
obshag ob[LEN];
long long get_cnt(int a);
int get_root(int u);
int get_root1(int v);
int main() {
  scanf("%i%i", &n, &m);
  for (int i = 0; i < n; i++) {
    ob[i].un = ob[i].voen = un[i].par = voen[i].par = i;
    un[i].cnt = un[i].h = voen[i].h = 1;
    un[i].lef = 0;
    voen[i].last = -1;
    un[i].ar.push_back(make_pair(-1, 0));
    voen[i].time = -1;
    ob[i].last = -1;
  }
  for (int i = 1; i <= m; i++) {
    scanf("%c", &ch);
    scanf("%c", &ch);
    if (ch == 'U') {
      scanf("%i %i", &a, &b);
      a = get_root(a - 1);
      b = get_root(b - 1);
      if (a == b) continue;
      if (un[a].h >= un[b].h) {
        un[b].lef = un[a].ar.size() - 1;
        un[b].par = a;
        un[a].cnt += un[b].cnt;
        if (un[a].h == un[b].h) un[a].h++;
      } else {
        un[a].lef = un[b].ar.size() - 1;
        un[a].par = b;
        un[b].cnt += un[a].cnt;
      }
    } else if (ch == 'M') {
      scanf("%i %i", &a, &b);
      a = get_root1(a - 1);
      b = get_root1(b - 1);
      if (a == b) continue;
      if (voen[a].h >= voen[b].h) {
        voen[b].par = a;
        voen[b].time = i;
        if (voen[a].h == voen[b].h) voen[a].h++;
      } else {
        voen[a].par = b;
        voen[a].time = i;
      }
    } else if (ch == 'A') {
      scanf("%i", &a);
      a = get_root(a - 1);
      un[a].ar.push_back(
          make_pair(i, un[a].cnt + un[a].ar[un[a].ar.size() - 1].second));
    } else if (ch == 'Z') {
      scanf("%i", &a);
      a = get_root1(a - 1);
      voen[a].last = i;
    } else {
      scanf("%i", &a);
      printf("%I64d\n", get_cnt(a - 1));
    }
  }
  return 0;
}
long long get_cnt(int a) {
  long long res = 0, u, v;
  int l, r, m, last, f = 0;
  u = ob[a].un;
  v = ob[a].voen;
  last = voen[v].last;
  while (v != voen[v].par) {
    if (voen[v].time < voen[voen[v].par].last)
      last = max(last, voen[voen[v].par].last);
    v = voen[v].par;
  }
  l = 0;
  while (f == 0 || u != un[u].par) {
    f = (u == un[u].par);
    r = un[u].ar.size();
    res += un[u].ar[r - 1].second;
    while (l + 1 < r) {
      m = (l + r) / 2;
      if (un[u].ar[m].first > last)
        r = m;
      else
        l = m;
    }
    if (r > 0) res -= un[u].ar[l].second;
    l = un[u].lef;
    u = un[u].par;
  }
  return res;
}
int get_root(int u) {
  while (u != un[u].par) u = un[u].par;
  return u;
}
int get_root1(int v) {
  while (v != voen[v].par) v = voen[v].par;
  return v;
}
