码迷,mamicode.com
首页 > 其他好文 > 详细

coursera Algorithms week1 练习测验2:Union-find with specific canonical element

时间:2017-07-19 11:50:10      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:continue   static   stdout   --   better   else   log   import   nec   

题目原文:

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

标签:continue   static   stdout   --   better   else   log   import   nec   

原文地址:http://www.cnblogs.com/evasean/p/7204540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!