并查集
2015-08-16 10:15
411 查看
public class Main { public static void main(String[] args) { UFSTree[] u = new UFSTree[11]; makeSet(u); union(u, 2, 4); union(u, 5, 7); union(u, 1, 3); union(u, 8, 9); union(u, 1, 2); union(u, 5, 6); union(u, 2, 3); System.out.println(isSimilar(u, 3, 4)); System.out.println(isSimilar(u, 7, 10)); System.out.println(isSimilar(u, 8, 9)); } public static void makeSet(UFSTree[] u) { for(int i = 1; i < u.length; i++) { u[i] = new UFSTree(); u[i].data = i; u[i].rank = 1; u[i].parent = i; } } public static void union(UFSTree[] u, int x, int y) { int root_1 = findRoot(u, x); int root_2 = findRoot(u, y); if(root_1 != root_2) { if(u[root_1].rank > u[root_2].rank) { u[root_2].parent = root_1; } else { u[root_1].parent = root_2; if(u[root_1].rank == u[root_2].rank) { u[root_2].rank++; } } } } public static int findRoot(UFSTree[] u, int x) { if(x != u[x].parent) { return findRoot(u, u[x].parent); } else { return x; } } public static boolean isSimilar(UFSTree[] u, int x, int y) { if(findRoot(u, x) == findRoot(u, y)) { return true; } else { return false; } } } class UFSTree { public int data; public int rank; public int parent; }
相关文章推荐
- 2015山东毕业生如何进行网上报道(报到证)?
- oracle 学习笔记之触发器
- Swift开发过程中常用到的一些使用技巧和注意的地方
- C#调Exe
- 《软件调试》要点整理
- c++ primer 学习笔记-第十章
- ContentProvider类的设计分析
- ie实现inline-block
- [家里蹲大学数学杂志]第413期插值不等式
- 编程之美1.13 威佐夫(NIM)博奕(Wythoff Game)涉及的数学定理论证
- poj 3107 Godfather 求树的所有重心 树形DP
- redis cluster
- uva 11806 容斥原理+二进制
- ADT导出Android工程到Androidstudio
- 【VB】MSHFlexGrid表格数据导出到Excel
- 历史疑团之EJB
- css 可继承属性
- C语言的输入输出
- shell-like program(shell程序的基本实施部分)
- shell-like program(shell程序的基本实施部分)