题目
给定一个包含 n 个点(编号为 1∼n)的无向图,初始时图中没有边
现在要进行 m 个操作,操作共有三种:
C a b,在点 a 和点 b 之间连一条边,a 和 b 可能相等
Q1 a b,询问点 a 和点 b 是否在同一个连通块中,a 和 b 可能相等
Q2 a,询问点 a 所在连通块中点的数量
输入
5 5
C 1 2
Q1 1 2
Q2 1
C 2 5
Q2 5
输出
Yes
2
3
public class 并查集_连通块中点的数量 {
//初始化
public static int N = 100010;
public static int[] p = new int[N], points = new int[N];
public static void main(String[] args) throws IOException {
//初始化
//注意p数组最开始每个点都为一个单独的集,根节点指向自己
//而points数组记录每个集中点的数量,初始全部为1
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] init_data = in.readLine().split(" ");
int n = Integer.parseInt(init_data[0]), m = Integer.parseInt(init_data[1]);
for (int i = 1; i<=n; i++){
p[i] = i;
points[i] = 1;
}
//执行操作
while (m-- > 0){
String[] data_arr = in.readLine().split(" ");
String model = data_arr[0];
//这里可以三个判断就够了,但是因为我是真的不想反复写Integer.parseInt(data_arr[])这个东西,看着也乱,就根据参数量分开吧
if (model.equals("Q2")) {
int x = Integer.parseInt(data_arr[1]);
//直接输出根节点在points数组中存的点的数量
System.out.println(points[find(x)]);
}
else {
int x = Integer.parseInt(data_arr[1]), y = Integer.parseInt(data_arr[2]);
if (model.equals("C")) {
//这个地方切记是先进行判断并且将x的点数加到y上,然后再进行合并集的操作,反过来的话这个if永远都不成立
if (find(x)!=find(y)) {points[find(y)] += points[find(x)];}
p[find(x)] = find(y);
}
else if (model.equals("Q1")) {
//判断x和y根节点是否相同
if (find(x)==find(y)) {System.out.println("Yes");}
else {System.out.println("No");}
}
}
}
}
//找到x的根节点,并且返回
public static int find(int x){
if (p[x]!=x) {p[x] = find(p[x]);}
return p[x];
}
}
声明:算法思路来源为y总,详细请见https://www.acwing.com/
本文仅用作学习记录和交流