1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class UnionFind{ public int num; public int[] father; public int[] depth; public UnionFind(int n){ num=n; father=new int[n]; depth=new int[n]; for(int i=0;i<n;i++){ father[i]=i; depth[i]=1; }
}
public boolean merge(int i,int j){ int rootX=find(i); int rootY=find(j); if(rootX==rootY){ return false; } if(depth[rootX]>depth[rootY]){ father[rootY]=rootX; depth[rootX]+=depth[rootY]; }else{ father[rootX]=rootY; depth[rootY]+=depth[rootX]; } num--; return true; }
public int find(int i){ if(father[i]!=i){ father[i]=find(father[i]); } return father[i]; } }
|