并查集模板:
-
建各自为集
-
找集合的代表节点
-
合并集合
-
判断两集合是否为同一集合
public static int maxN=100001;
//每个节点的代表节点
public static int[] father=new int[maxN];
//各自为集
public void build(){
for (int i = 0; i < father.length; i++) {
father[i]=i;
}
}
//找各节点的代表节点
public int find(int i){
if (i!=father[i]){
father[i]=find(father[i]);
}
return father[i];
}
//合并集合
public void union(int x,int y){
father[find(x)]=find(y);
}
//判断是否为同意集合
public boolean isSameSet(int x,int y){
return find(x)==find(y);
}