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

Posted evasean

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

Coursera Algorithms week1 Interview Questions: 3Sum in quadratic time

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

Princeton-Algorithms-Part1-Week1-Percolation

Coursera TensorFlow 基础课程-week1

Coursera机器学习week1 笔记

Coursera TensorFlow 基础课程-week1