19874并查集
⭐️难度:中等
🌟考点:并查集、数据结构
📖
📚
import java.util.*;
public class Main {
static int N = 100010;
static int[] a = new int[N];
static int[] p = new int[N];
static int n;
static int m;
static int find(int x){ // 路径优化
return p[x] == x? x : (p[x] = find(p[x]));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
for (int i = 1; i <= n; i++) {
a[i] = i;
p[a[i]] = i; // 初始化
}
while(m-->0){
String op = sc.next();
int a = sc.nextInt();
int b = sc.nextInt();
if(op.equals("M")){
p[find(b)] = find(a);
}else{
if(find(a)==find(b)){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
}
}
}