加权路径压缩并查集实现
2015-10-16 10:13
141 查看
package algs4; import edu.princeton.cs.algs4.StdIn; import edu.princeton.cs.algs4.StdOut; import java.io.FileInputStream; import java.io.InputStream; /** * 并查集 * Created by blank on 2015-10-15 下午8:56. */ public class UF { public static void main(String[] args) throws Exception { InputStream input = new FileInputStream(Constants.PATH + "largeUF.txt"); System.setIn(input); int N = StdIn.readInt(); UF uf = new UF(N); while (N-- > 0) { int p = StdIn.readInt(); int q = StdIn.readInt(); if (uf.connected(p, q)) continue; uf.union(p, q); // StdOut.println(p + " " + q); } StdOut.println(uf.getCount() + " components"); } private int[] parent; private byte[] rank; private int count; public UF(int n) { count = n; parent = new int ; rank = new byte ; for (int i = 0; i < n; i++) { parent[i] = i; rank[i] = 0; } } public int getCount() { return count; } public boolean connected(int p, int q) { return find(p) == find(q); } private int find(int p) { while (p != parent[p]) { parent[p] = parent[parent[p]]; p = parent[p]; } return p; } public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) { return; } if (rank[rootP] < rank[rootQ]) { parent[rootP] = rootQ; } else if (rank[rootP] > rank[rootQ]) { parent[rootQ] = rootP; } else { parent[rootP] = rootQ; rank[rootQ]++; } count--; } }
相关文章推荐
- cocos2dx3.0 超级马里奥开发笔记(两)——正确的规划游戏逻辑
- 获取订单的product_id 和订单的数量
- ssh免密码登录
- Android Annotations 注解标签
- 关于Syncovery软件在windows下远程访问服务器批量拷贝文件的使用
- 【Bugly 一岁了】所有的努力,都需要时间的鉴证。
- eclipse maven plugin 插件 安装 和 配置
- 【C#基础】初探.Net内存分配原理
- 百度JSP版坐标转换 限定不大于10个每次的处理办法
- 如何设置单元格分割线的缩进?
- 窗宽窗位与其处理方法
- HowTo Install Redmine 2.5.x on Fedora 20
- MyBatis初探
- maven jdk 版本配置
- 加锁的原因 结构体内部增加锁
- Eclipse中集成Tomcat
- Java用itext操作PDF
- MyEclipse在Java文件中设置作者、日期
- 查询某条记录在数据库中是 第几行
- Linux 命令 - find: 搜索文件