您的位置:首页 > 其它

并查集不知道哪里出错了

2018-03-31 09:30 239 查看
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)]);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: