首页 > 代码库 > coursera Algorithms week1 练习测验2:Union-find with specific canonical element
coursera Algorithms week1 练习测验2: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.
1 import edu.princeton.cs.algs4.StdIn; 2 import edu.princeton.cs.algs4.StdOut; 3 4 public class FindLargestUF { 5 private int[] id; 6 private int count; 7 public FindLargestUF(int n) { 8 count = n; 9 id = new int[n]; 10 for (int i = 0; i < n; i++) 11 id[i] = i; 12 } 13 public int count(){ 14 return count; 15 } 16 public boolean connected(int p, int q){ 17 return (find(p)==find(q)); 18 } 19 public int find(int p) { 20 while (p != id[p]) 21 p = id[p]; 22 return p; 23 } 24 25 public void union(int p, int q) { 26 int pRoot = find(p); 27 int qRoot = find(q); 28 StdOut.println("find("+p+")="+pRoot+",find("+q+")="+qRoot); 29 if (pRoot == qRoot) 30 return; 31 else if (pRoot < qRoot) 32 id[pRoot] = qRoot; 33 else 34 id[qRoot] = pRoot; 35 count--; 36 } 37 38 public static void main(String[] args) { 39 int n = StdIn.readInt(); 40 FindLargestUF uf = new FindLargestUF(n); 41 while (!StdIn.isEmpty()) { 42 int p = StdIn.readInt(); 43 int q = StdIn.readInt(); 44 if (uf.connected(p, q)) 45 continue; 46 uf.union(p, q); 47 StdOut.println("link points:" + p + " " + q); 48 } 49 StdOut.println(uf.count() + "components"); 50 } 51 }
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
coursera Algorithms week1 练习测验2:Union-find with specific canonical element
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。