AcWing 837. 连通块中点的数量 Java
原题链接
简单
作者:
leo_0
,
2020-07-14 13:09:23
,
所有人可见
,
阅读 469
题目描述
算法1
Java 代码
import java.io.*;
import java.util.*;
public class Main {
static class UFind {
int[] father;
int[] size;
UFind(int n){
father = new int[n+1];
size = new int[n+1];
for(int i = 1; i <= n; i++){
father[i] = i;
size[i] = 1;
}
}
public int find(int x) {
if(father[x] != x){
father[x] = find(father[x]);
}
return father[x];
}
public void union(int p, int q) {
int fp = find(p);
int fq = find(q);
if(fp != fq){
father[fp] = fq;
size[fq] += size[fp];
}
}
}
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws Exception {
String[] s = read.readLine().split(" ");
int n = Integer.valueOf(s[0]);
int m = Integer.valueOf(s[1]);
UFind uf = new UFind(n);
for(int i = 0; i < m; i++){
s = read.readLine().split(" ");
if("C".equals(s[0])){
uf.union(Integer.valueOf(s[1]), Integer.valueOf(s[2]));
}else if("Q1".equals(s[0])){
int f1 = uf.find(Integer.valueOf(s[1]));
int f2 = uf.find(Integer.valueOf(s[2]));
String out = f1 == f2 ? "Yes" : "No";
log.write(out + "\n");
}else{
int f = uf.find(Integer.valueOf(s[1]));
log.write(uf.size[f] + "\n");
}
}
log.flush();
}
}