AcWing 837. 连通块中点的数量-Java
原题链接
简单
作者:
Susu
,
2020-01-28 23:56:00
,
所有人可见
,
阅读 712
import java.io.*;
public class Main{
static int N = 100010;
static int[] p = new int[N];
static int m;
static int n;
static int[] size = new int[N];
static int find(int x){
if(p[x]!=x) p[x]=find(p[x]);
return p[x];
}
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s = br.readLine().split(" ");
int n = Integer.valueOf(s[0]);
int m = Integer.valueOf(s[1]);
for(int i=1;i<=n;i++){
p[i]=i;
size[i]=1;
}
while(m-->0){
String[] strs = br.readLine().split(" ");
if(strs[0].equals("C")){
int a = Integer.valueOf(strs[1]);
int b = Integer.valueOf(strs[2]);
if(find(a)!=find(b)){
size[find(b)]+=size[find(a)];//看好选B的祖宗作为根,只保留根节点的size
p[find(a)]=find(b);
}
}else if(strs[0].equals("Q1")){
int a = Integer.valueOf(strs[1]);
int b = Integer.valueOf(strs[2]);
if(find(a)!=find(b)) System.out.println("No");
else System.out.println("Yes");
}else{
int a = Integer.valueOf(strs[1]);
System.out.println(size[find(a)]);
}
}
}
}