AcWing 837. 连通块中点的数量
原题链接
简单
作者:
鸡娃练习生
,
2024-10-23 14:57:22
,
所有人可见
,
阅读 1
import java.util.*;
import java.io.*;
public class Main{
static int N = 100010;
static int[] arr = new int[N];//表示存储点
static int[] sums = new int[N];//存储每个连通块有多少个点
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
int m = Integer.parseInt(str[1]);
for(int i = 1;i <= n;i++){
arr[i] = i;
sums[i] = 1;
}
while(m-- > 0){
str = br.readLine().split(" ");
String x = str[0];
if(x.equals("C")){
int a = Integer.parseInt(str[1]);
int b = Integer.parseInt(str[2]);
if(find(a) != find(b)){//考虑ab可能相等的情况
sums[find(b)] += sums[find(a)];
arr[find(a)] = find(b);
}
}else if(x.equals("Q1")){
int a = Integer.parseInt(str[1]);
int b = Integer.parseInt(str[2]);
if(find(a) == find(b) ){
System.out.println("Yes");
}else{
System.out.println("No");
}
}else{
int a = Integer.parseInt(str[1]);
System.out.println(sums[find(a)]);
}
}
}
static int find(int x){
if(arr[x] != x){
arr[x] = find(arr[x]);
}
return arr[x];
}
}