-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathWeightedTreeDisjointSet.cs
More file actions
48 lines (38 loc) · 1.05 KB
/
WeightedTreeDisjointSet.cs
File metadata and controls
48 lines (38 loc) · 1.05 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
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;
}
}