java---并查集算法---连通块中点的数量(每日一道算法2022.8.13)

题目
给定一个包含 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/
本文仅用作学习记录和交流

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值