并查集-合并集合
#include<iostream>
using namespace std;
const int N = 100010;
int n, m;
int a, b;
int fa[N];
char opt;
int find(int x) {
if (fa[x] == x) return x;
return fa[x] = find(fa[x]); //这里做了路径压缩优化,先让查找到最后的祖宗,最后依次让点指向祖宗
}
void merge(int x, int y) {
fa[find(x)] = find(y);
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i ++ ) fa[i] = i;
while(m -- ) {
cin >> opt;
if (opt == 'M') {
cin >> a >> b;
merge(a, b);
}
if (opt == 'Q') {
cin >> a >> b;
if (find(a) == find(b)) cout << "Yes" << endl;
else cout << "No" << endl;
}
}
}