并查集系列(二)——Union-find with specific canonical element
来源:互联网 发布:汉字意义 知乎 编辑:程序博客网 时间:2024/06/03 22:48
问题描述
Union-find with specific canonical element. Add a method find() to the union-find data type so that find(i) returns the largest element in the connected component containing i. The operations, union(), connected(), and find() should all take logarithmic time or better. For example, if one of the connected components is {1,2,6,9}, then the find() method should return 9 for each of the four elements in the connected components.
思路分析
通过添加一个数组来完成对于每个树最大值进行维护
JAVA代码实现
public class FindMax { private int[] max = new int[10]; // 每个节点对应树的最大值 private int[] roots = new int[10]; // 每个点的父节点 private int[] points = new int[10]; // 每个点所在树的节点数量 public FindMax(){ for (int i = 0; i < roots.length; i++) { roots[i] = i; } for (int i = 0; i < points.length; i++) { points[i] = 1; } for (int i = 0; i < max.length; i++) { max[i] = i; } } public int find(int a){ return max[root(a)]; } public void union(int a, int b) { int rootA = root(a); int rootB = root(b); if (root(rootA) != root(rootB)) { if (points[rootA] < points[rootB]) { roots[rootA] = rootB; points[rootB] += points[rootA]; if(max[rootA]> max[rootB]) max[rootB] = max[rootA]; } if (points[rootB] <= points[rootA]) { roots[rootB] = rootA; points[rootA] += points[rootB]; if(max[rootB]> max[rootA]) max[rootA] = max[rootB]; } } } public int root(int a) { while (roots[a] != a) { a = roots[a]; } return a; } public static void main(String[] args) { FindMax find = new FindMax(); find.union(1, 2); find.union(1, 4); find.union(4, 6); find.union(5, 2); System.out.println(find.find(2)); }}
运行结果:
6
0 0
- 并查集系列(二)——Union-find with specific canonical element
- coursera Algorithms week1 练习测验2:Union-find with specific canonical element
- LeetCode Union-Find(并查集) 专题(二)
- 并查集算法(Union-Find)
- 并查集(Union-Find Set)
- Union-Find 算法(并查集)
- 并查集:Union-Find(1)
- 并查集算法(union-find)
- 并查集(Union Find)
- 并查集(Union Find)简介
- uva11987Almost Union-Find (并查集)
- 并查集(Union-find Sets)
- 算法合集——并查集union-find
- 并查集——Union-Find算法
- 并查集(Union-Find)
- Union Find 并查集
- 并查集Union--Find
- 并查集Union-Find
- 绘制地图:图形化显示海地地震危机数据
- Java&Android入门学习方法及书目推荐
- 解决Jackson的jar包导入,程序无法正常运行问题
- swift 学习笔记(5)-元组
- 安卓高德地图定位
- 并查集系列(二)——Union-find with specific canonical element
- python 三层架构
- python 中的排序大法
- IRP 处理流程
- Truncated class file 截断的class文件
- LeetCode No.279 Perfect Squares
- 浮点型数据在内存中存储的表示[转载]
- asp.net 资料收集
- 使用C#开发ActiveX控件