coursera Algorithms week1 练习测验2:Union-find with specific canonical element
来源:互联网 发布:java 时间戳 时区 编辑:程序博客网 时间:2024/06/06 13:25
题目原文:
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.
分析:
这一题很简单,要求find到的根是子集中的最大元素。因此只需要在union时,用两个子集中较大的root作为合并后的root就可以了。以下代码提交100
import edu.princeton.cs.algs4.StdIn;import edu.princeton.cs.algs4.StdOut;public class FindLargestUF {private int[] id;private int count;public FindLargestUF(int n) {count = n;id = new int[n];for (int i = 0; i < n; i++)id[i] = i;}public int count(){return count;}public boolean connected(int p, int q){return (find(p)==find(q));}public int find(int p) {while (p != id[p])p = id[p];return p;}public void union(int p, int q) {int pRoot = find(p);int qRoot = find(q);StdOut.println("find("+p+")="+pRoot+",find("+q+")="+qRoot);if (pRoot == qRoot)return;else if (pRoot < qRoot)id[pRoot] = qRoot;elseid[qRoot] = pRoot;count--;}public static void main(String[] args) {int n = StdIn.readInt();FindLargestUF uf = new FindLargestUF(n);while (!StdIn.isEmpty()) {int p = StdIn.readInt();int q = StdIn.readInt();if (uf.connected(p, q))continue;uf.union(p, q);StdOut.println("link points:" + p + " " + q);}StdOut.println(uf.count() + "components");}}
阅读全文
0 0
- coursera Algorithms week1 练习测验2:Union-find with specific canonical element
- Coursera Algorithms week1 练习测验3:Successor with delete
- 并查集系列(二)——Union-find with specific canonical element
- Coursera Algorithms week1 练习测验1:Social network connectivity
- Coursera Algorithms, Part 1 Week 1: Union-Find
- Coursera Algorithms week1 Interview Questions: Egg drop
- Week1-5Union-Find Applications
- Coursera Algorithms week1 Interview Questions: 3Sum in quadratic time
- Coursera Algorithms week1 Interview Questions: Search in a bitonic array
- Week1-2Quick Find
- Coursera 吴恩达 DeepLearning.ai 第2课 Improving Deep Neural Networks 第二周 测验题 Optimization algorithms
- Coursera课程 R-Programming Week1 编程练习代码
- Find the element before and after a specific element
- 【Coursera】Algorithms, Part I 算法C++实现: Quick Union
- 【Coursera】Algorithms, Part I 算法C++实现:Weighted Quick Union
- Algorithms 学习笔记01 Union Find
- Find Tables with Specific Field Names
- Algorithms—162.Find Peak Element
- FormData和multer使用的一个小坑
- OpenResty(Nginx+Lua)
- hdu2037——今年暑假不AC
- Django搭建微信后端(1)---回复消息和自定义菜单
- 【SQL】JDBC之与数据库MySQL的连接以及增删改查等操作
- coursera Algorithms week1 练习测验2:Union-find with specific canonical element
- PostgreSQL
- MySql存储过程与函数详解
- 牛客网编程题:获取url中的参数
- B1032. 挖掘机技术哪家强(20)
- Mycat之——Mycat在MySQL主从复制基础上实现读写分离
- Android音频系统之AudioFlinger(三)
- Java提高篇——Java 异常处理
- jQuery初识,常用的选择器、Ajax