-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnionFind.cs
53 lines (44 loc) · 1.24 KB
/
UnionFind.cs
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
namespace rac.so.bytehaven
{
public class UnionFind
{
/* An implementation of the Union-Find data structure. MIT License.
Made with ♠ by Racso. https://rac.so | https://github.com/Racso */
private readonly int[] parent;
private readonly int[] rank;
public UnionFind(int capacity)
{
parent = new int[capacity];
rank = new int[capacity];
for (int i = 0; i < capacity; i++)
{
parent[i] = i;
rank[i] = 1;
}
}
public int FindSet(int n)
{
if (parent[n] == n)
return n;
parent[n] = FindSet(parent[n]);
return parent[n];
}
public bool Union(int n, int m)
{
int nRoot = FindSet(n);
int mRoot = FindSet(m);
if (nRoot == mRoot)
return false;
if (rank[nRoot] > rank[mRoot])
parent[mRoot] = nRoot;
else if (rank[nRoot] < rank[mRoot])
parent[nRoot] = mRoot;
else
{
parent[mRoot] = nRoot;
rank[nRoot]++;
}
return true;
}
}
}