并查集不知道哪里出错了

时间:2021-09-16 14:45:30
package com.company;
import java.util.*;
public class Main{
    //并查集
    static int N, M;//N个数字,M个操作
    static int[]bcj=new int[10001];
    static Scanner sc=new Scanner(System.in);
    static int Find(int x){
        if(bcj[x]<0) return x;
        return bcj[x]=Find(bcj[x]);
    }
    static void Union(int x, int y){
        x=Find(x);
        y=Find(y);
        if(x==y) return;
        bcj[x]+=bcj[y];
        bcj[y]=x;
    }
    public static void main(String[] args){
        N=sc.nextInt();
        M=sc.nextInt();
        int i, x, y;
        String[] com={"Union", "Find", "Count"};
        for(i=1; i<=N; i++) bcj[i]=-1;
        for(i=1; i<=M; i++){
            if(sc.next()==com[0]){
                x=sc.nextInt();
                y=sc.nextInt();
                Union(x, y);
            }
            if(sc.next()==com[1]){//Find
                x=sc.nextInt();
                y=sc.nextInt();
                if(Find(x)==Find(y)) System.out.println("True");
                System.out.println("False");
            }
            if(sc.next()==com[2]){
                x=sc.nextInt();
                System.out.println(-bcj[Find(x)]);
            }
        }
    }
}