public class DisjointSet {
static int VERTICES=6;
public static void init(int[] parent,int[]rank) {
for(int i=0;i<VERTICES;i++) {
parent[i]=-1;
rank[i]=-1;
}
}
public static int findroot(int x,int[] parent) {
int xroot=x;
while (parent[xroot]!=-1) {
xroot=parent[xroot];
}
return xroot;
}
public static int unionV(int x,int y,int[] parent,int[] rank) {
int xroot=findroot(x, parent);
int yroot=findroot(y, parent);
if(xroot==yroot) {
return 0;
}
else {
if(rank[xroot]>rank[yroot]) {
parent[yroot]=xroot;
return 1;
}
else if (rank[xroot]<rank[yroot]) {
parent[xroot]=yroot;
return 1;
}
else {
parent[yroot]=xroot;
rank[xroot]+=1;
return 1;
}
}
}
public static void main(String[] args) {
int[][] edges = {{0,1},{1,2},{1,3},{4,5},{2,5},{1,5}};
int [] parent = new int[VERTICES];
int [] rank = new int[VERTICES];
init(parent,rank);
for(int i=0;i<edges.length;i++) {
int x=edges[i][0];
int y=edges[i][1];
if(unionV(x,y,parent,rank)==0) {
System.err.println("存在环");
System.exit(0);
}
}
for(int j=0;j<6;j++) {System.err.print(rank[j]+" ");}
System.err.println("\n");
for(int j=0;j<6;j++) {System.err.print(parent[j]+" ");}
System.err.println("\n");
System.err.println("\n没有环");
}
}
![代码中示例数据的构造过程](https://i-blog.csdnimg.cn/blog_migrate/479dfd01022470934e0826864a6c024a.jpeg#pic_center)