File tree Expand file tree Collapse file tree 2 files changed +94
-0
lines changed
Expand file tree Collapse file tree 2 files changed +94
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .Random ;
2+
3+ public class Main {
4+ private static double testUF (UF uf , int m ) {
5+ int size = uf .getSize ();
6+ Random random = new Random ();
7+
8+ long startTime = System .nanoTime ();
9+
10+ // 执行 m 次合并操作
11+ for (int i = 0 ; i < m ; i ++) {
12+ int a = random .nextInt (size );
13+ int b = random .nextInt (size );
14+ uf .unionElements (a , b );
15+ }
16+
17+ // 执行 m 次查询操作
18+ for (int i = 0 ; i < m ; i ++) {
19+ int a = random .nextInt (size );
20+ int b = random .nextInt (size );
21+ uf .isConnected (a , b );
22+ }
23+
24+
25+ long endTime = System .nanoTime ();
26+
27+ return (endTime - startTime ) / 1000000000.0 ;
28+
29+ }
30+
31+ public static void main (String [] args ) {
32+ int size = 100000 ;
33+ int m = 10000 ;
34+
35+
36+ UnionFind1 uf1 = new UnionFind1 (size );
37+ System .out .println ("UnionFind1 : " + testUF (uf1 , m ) + " s" );
38+
39+
40+ UnionFind2 uf2 = new UnionFind2 (size );
41+ System .out .println ("UnionFind2 : " + testUF (uf2 , m ) + " s" );
42+
43+ }
44+ }
Original file line number Diff line number Diff line change 1+ public class UnionFind2 implements UF {
2+
3+ private int [] parent ;
4+
5+ public UnionFind2 (int size ) {
6+ parent = new int [size ];
7+
8+ for (int i = 0 ; i < size ; i ++) {
9+ parent [i ] = i ;
10+ }
11+ }
12+
13+ @ Override
14+ public int getSize () {
15+ return parent .length ;
16+ }
17+
18+ // 查找过程,查找元素p对应的集合编号
19+ // O(h)复杂度,h为树的高度
20+ private int find (int p ) {
21+
22+ if (p < 0 && p >= parent .length ) {
23+ throw new IllegalArgumentException ("p is out of bound" );
24+ }
25+
26+ while (p != parent [p ]) {
27+ p = parent [p ];
28+ }
29+ return p ;
30+ }
31+
32+ // 查看元素p和元素q是否所属一个集合
33+ @ Override
34+ public boolean isConnected (int p , int q ) {
35+ return find (p ) == find (q );
36+ }
37+
38+ // 合并元素p和元素q所属的集合
39+ // O(h) 复杂度,h为树的高度
40+ @ Override
41+ public void unionElements (int p , int q ) {
42+ int pRoot = find (p );
43+ int qRoot = find (q );
44+ if (pRoot == qRoot ) {
45+ return ;
46+ }
47+ parent [pRoot ] = qRoot ;
48+
49+ }
50+ }
You can’t perform that action at this time.
0 commit comments