-
Notifications
You must be signed in to change notification settings - Fork 2
/
UnionFind.java
executable file
·50 lines (45 loc) · 1.1 KB
/
UnionFind.java
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
import java.util.*;
class UnionFind {
int[] elms;
/**Data structure for working with grouping of elements
* o(n)
* @param n The number of elements*/
UnionFind(int n) {
elms = new int[n];
Arrays.fill(elms, -1);
}
/**Which group does v belong to?
* O(log* n)
* @param v The element whose group to find
* @return The group v belongs to*/
int find(int v) {
if(elms[v] < 0)
return v;
else
return (elms[v] = find(elms[v]));
}
/**Join the group v belongs to and the group u belongs to
* O(log* n)
* @param v An element in the first group
* @param w An element in the second group*/
void join(int v, int w) {
v = find(v);
w = find(w);
if(v == w)
return;
if(elms[v] > elms[w]) {
int temp = v;
v = w;
w = temp;
}
elms[v] += elms[w];
elms[w] = v;
}
/**How many elements are there in the group v belongs to?
* O(log* n)
* @param v An element in the group
* @return The size of the group*/
int size(int v) {
return -elms[find(v)];
}
}