看网上的find函数几乎都不是用递归写的 找模板用了还是挺长时间的 就自己写了一份(备忘)我是初学者别喷我呜呜 不过算法真的越学越有意思啊
package 并查集;
public class fondation {
static int[]parent;//使用数组存储每一个人的上级
static int count;//记录全体人数目
static int rank[];
public static void all(int numElements){
parent = new int[numElements];
for(int i=0;i<parent.length;i++){
parent[i] = i;//一开始所有人的上级都是自己
}
}
public static void union(int root1,int root2){//合并
//将root1作为root2的新树根
parent[root2] = root1;
}
public static int find(int x){//查找
if(parent[x]==x)
return x;
else
return find(parent[x]);
}
public static int find2(int x){//压缩路径查找 指这段链上的全部人的上级直接修改成最高级
if(parent[x] == x)
return x;
else
return parent[x] = find2(parent[x]);
}
public static void union2(int root1,int root2){//优化合并算法 需要事先开一个数组(rank[])记录每个人的所有上级数目
//如果root1和root2属于同一链上,则不用合并
if(find(root1) == find(root2))
return;
if(rank[root1] > rank[root2])//root1的人多 就把root1作为上级
parent[root2] = root1;
else
parent[root1] = root2;
}
}
有用的话点个赞?接着会更新并查集基本题目(当前全是java 毕竟学软件的我只会用java和py和MATLAB(太菜了))