1. 程式人生 > >coursera Algorithms week1 練習測驗2:Union-find with specific canonical element

coursera Algorithms week1 練習測驗2:Union-find with specific canonical element

data take log pre n) nbsp -- poi take for

題目原文:

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