并查集:连通块中点的数量

 


import java.io.*;
import java.util.Scanner;

public class Main{
    static int N = 100010;
    static int[] p = new int[N];    //存储每个节点的父亲节点,一开始默认p[i]=i;
    static int[] size = new int[N]; //存储每个连通块里含有多少个节点
    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
    public static int find(int x){
        if (p[x] != x) p[x] = find(p[x]);
        return p[x];
    }
    public static void main(String[] args) throws IOException {
        String[] init = in.readLine().split(" ");
        int n = Integer.parseInt(init[0]);
        int m = Integer.parseInt(init[1]);
        for (int i = 1; i <= n; i++) {
            p[i] = i;
            size[i] = 1;
        }

        while (m-->0){
            init = in.readLine().split(" ");
            String x = init[0];

            //区间合并
            //已经在一个集合里的话需要特判,如果不特判的话,集合内的size会翻倍(实际不用变)
            if (x.equals("C"))
            {

                int a = Integer.parseInt(init[1]);
                int b = Integer.parseInt(init[2]);
                if (find(a) != find(b)) {
                    //将a的size加到b中(只有根节点的size有效)
                    size[find(b)] +=size[find(a)];
                    //把a的集合的根节点的父亲设置成b的根节点
                    p[find(a)] = find(b);
                    
                    //这两行不能交换,如果交换的话
                    //比如a最上面的根节点是6,b最上面的根节点是7
                    //把b作为a图的根节点的父亲
                    //因为只有根节点的size有用,这样的话find(a)和find(b)都是7
                    //这样的话会让size翻倍,a图的6不会起作用
                    //所以要先把size加上
                }
                //将a祖宗的父亲设置成b的祖宗
            }
            else if (x.equals("Q1")){
                //是否同一个集合
                int a = Integer.parseInt(init[1]);
                int b = Integer.parseInt(init[2]);
                if (find(a) == find(b)) out.write("Yes");
                else out.write("No");
                out.newLine();
            } else {
                int a = Integer.parseInt(init[1]);
                out.write(size[find(a)] + " ");
                out.newLine();
            }
        }
        in.close();
        out.flush();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值