-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathWeightedQuickUnionUF.java
More file actions
54 lines (48 loc) · 1.13 KB
/
Copy pathWeightedQuickUnionUF.java
File metadata and controls
54 lines (48 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class WeightedQuickUnionUF
{
private int[] id;
private int[] sz;
private int N;
public WeightedQuickUnionUF(int N)
{
this.id = new int[N];
this.sz = new int[N];
this.N = N;
// every element in its connected component
for (int i = 0; i < N; i++)
{
id[i] = i;
sz[i] = 1;
}
}
private int root(int i)
{
while (i != id[i])
{
id[i] = id[id[i]]; // path compression...flatter trees
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 p_root = root(p);
int q_root = root(q);
if (connected(p_root, q_root)) return;
// make smaller tree the sub-tree of larger tree
if (sz[p_root] < sz[q_root])
{
id[p_root] = q_root;
sz[q_root] += sz[p_root];
}
else
{
id[q_root] = p_root;
sz[p_root] += sz[q_root];
}
}
}