AcWing 836. 合并集合Java
原题链接
简单
作者:
w972314191
,
2022-12-02 11:01:30
,
所有人可见
,
阅读 117
代码
import java.util.*;
import java.io.*;
public class Main{
static int N = 100010;
static int[] p = new int[N];
static int findFather(int x){
if(p[x] != x) p[x] = findFather(p[x]);
return p[x];
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
Integer[] line0 = Arrays.stream(br.readLine().split(" ")).map(Integer::parseInt).toArray(Integer[]::new);
int n = line0[0];
int m = line0[1];
for(int i = 0; i < n; i++){
p[i] = i;
}
while(m-->0){
String[] line = br.readLine().split(" ");
String op = line[0];
int a = Integer.parseInt(line[1]) - 1;
int b = Integer.parseInt(line[2]) - 1;
if(op.compareTo("M") == 0){
p[findFather(p[b])] = findFather(p[a]);
}
else{
if(findFather(p[a]) == findFather(p[b])){
bw.write("Yes\n");
}else{
bw.write("No\n");
}
}
}
br.close();
bw.flush();
bw.close();
}
}