File tree Expand file tree Collapse file tree 2 files changed +68
-1
lines changed
Expand file tree Collapse file tree 2 files changed +68
-1
lines changed Original file line number Diff line number Diff line change @@ -30,7 +30,7 @@ private static double testUF(UF uf, int m) {
3030
3131 public static void main (String [] args ) {
3232 int size = 100000 ;
33- int m = 10000 ;
33+ int m = 100000 ;
3434
3535
3636 UnionFind1 uf1 = new UnionFind1 (size );
@@ -40,5 +40,9 @@ public static void main(String[] args) {
4040 UnionFind2 uf2 = new UnionFind2 (size );
4141 System .out .println ("UnionFind2 : " + testUF (uf2 , m ) + " s" );
4242
43+
44+ UnionFind3 uf3 = new UnionFind3 (size );
45+ System .out .println ("UnionFind3 : " + testUF (uf3 , m ) + " s" );
46+
4347 }
4448}
Original file line number Diff line number Diff line change 1+ public class UnionFind3 implements UF {
2+
3+ private int [] parent ;
4+ private int [] sz ;
5+
6+ public UnionFind3 (int size ) {
7+ parent = new int [size ];
8+ sz = new int [size ];
9+
10+ for (int i = 0 ; i < size ; i ++) {
11+ parent [i ] = i ;
12+ sz [i ] = 1 ;
13+ }
14+ }
15+
16+ @ Override
17+ public int getSize () {
18+ return parent .length ;
19+ }
20+
21+ // 查找过程,查找元素p对应的集合编号
22+ // O(h)复杂度,h为树的高度
23+ private int find (int p ) {
24+
25+ if (p < 0 && p >= parent .length ) {
26+ throw new IllegalArgumentException ("p is out of bound" );
27+ }
28+
29+ while (p != parent [p ]) {
30+ p = parent [p ];
31+ }
32+ return p ;
33+ }
34+
35+ // 查看元素p和元素q是否所属一个集合
36+ @ Override
37+ public boolean isConnected (int p , int q ) {
38+ return find (p ) == find (q );
39+ }
40+
41+ // 合并元素p和元素q所属的集合
42+ // O(h) 复杂度,h为树的高度
43+ @ Override
44+ public void unionElements (int p , int q ) {
45+ int pRoot = find (p );
46+ int qRoot = find (q );
47+ if (pRoot == qRoot ) {
48+ return ;
49+ }
50+
51+
52+ // 基于 size 优化 quick union
53+ // 根据两个元素所在树的元素个数不同判断合并方向
54+ // 将元素个数少的集合合并到元素个数多的集合上
55+ if (sz [pRoot ] < sz [qRoot ]) {
56+ parent [pRoot ] = qRoot ;
57+ sz [qRoot ] += sz [pRoot ];
58+ } else { // sz[pRoot] <= sz[qRoot]
59+ parent [qRoot ] = pRoot ;
60+ sz [pRoot ] += sz [qRoot ];
61+ }
62+ }
63+ }
You can’t perform that action at this time.
0 commit comments