使用数组root存储父节点的值
root[i]=x,如果x<0,表示i是一个集合的根结点,且这个集合有abs(x)个结点;如果x>=0,则表示x是结点i的父节点
优化方法:压缩路径、按秩归并(将小的集合合并到大的集合)
int[] root = new int[1005];
int findRoot(int x){
if(root[x]<0)
return x;
return root[x]=findRoot(root[x]);//compressed path
}
void union(int x,int y){
int u = findRoot(x);
int v = findRoot(y);
if(u != v) {
if (root[u] < root[v]) {//combine small collections into large collections
root[u] += root[v];
root[v] = u;
} else {
root[v] += root[u];
root[u] = v;
}
}
}
}