-
Notifications
You must be signed in to change notification settings - Fork 1
/
WeightedTreeDisjointSet.cs
58 lines (49 loc) · 1.33 KB
/
WeightedTreeDisjointSet.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
54
55
56
57
58
namespace AlgorithmsAndDataStructures.DataStructures.DisjointSet
{
public class WeightedTreeDisjointSet : IDisjointSet
{
private readonly int[] set;
private readonly int[] weight;
public WeightedTreeDisjointSet(int size)
{
set = new int[size];
weight = new int[size];
for (var i = 0; i < size; i++)
{
set[i] = i;
}
for (var i = 0; i < size; i++)
{
weight[i] = 1;
}
}
public bool Connected(int a, int b)
{
return FindRoot(a) == FindRoot(b);
}
public void Union(int a, int b)
{
var aRoot = FindRoot(a);
var bRoot = FindRoot(b);
if (weight[aRoot] >= weight[bRoot])
{
set[bRoot] = aRoot;
weight[aRoot] = weight[aRoot] + weight[bRoot];
}
else
{
set[aRoot] = bRoot;
weight[bRoot] = weight[aRoot] + weight[bRoot];
}
}
private int FindRoot(int a)
{
var current = a;
while (current != set[current])
{
current = set[set[current]];
}
return current;
}
}
}