Princeton大學教授演算法課程weekone one
阿新 • • 發佈:2018-12-24
Quick-Union,lazy-approch.
Data Structure
1、Integer array id[] of size n
2、Interpretation:id[i] is parent of i
3、Root of i is id[id[id[i]]]… until it can’t change
we think about the arrray as a forest with a lot of trees.(take care)
as you can see from this picture ,9 is the father and 2、4、3 are its sons.
use this data structure we can find these connected components.
Find check if p and q have the same root.
Union to merge components containing p and q,set the id of p’s root to the id of q’s root.
now,we should see this process.
now id[4]=3
now id[3]=8.
as the array shows
as the array shows
package weekone; public class QuickUnionUF { private int [] id; public QuickUnionUF(int n) { id = new int[n]; for(int i=0;i<n;i++) { id[i]=i; } } private int root(int i) { while(i!=id[i]) i=id[i]; return i; } public boolean connected(int p,int q) { return root(p)==root(q); } public void union(int p,int q) { int i=root(p); int j=root(q); id[i]=j; } public static void main(String[] args) { QuickUnionUF s =new QuickUnionUF(10); s.union(4,3); s.union(3,8); s.union(9,8); System.out.println(s.connected(4,9)); } }
and the result is true.