forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DisjointSet.cs
62 lines (57 loc) · 1.68 KB
/
DisjointSet.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
59
60
61
62
using System.Collections;
namespace DataStructures.DisjointSet
{
/// <summary>
/// Implementation of Disjoint Set with Union By Rank and Path Compression heuristics.
/// </summary>
/// <typeparam name="T"> generic type for implementation.</typeparam>
public class DisjointSet<T>
{
/// <summary>
/// make a new set and return its representative.
/// </summary>
/// <param name="x">element to add in to the DS.</param>
/// <returns>representative of x.</returns>
public Node<T> MakeSet(T x) => new(x);
/// <summary>
/// find the representative of a certain node.
/// </summary>
/// <param name="node">node to find representative.</param>
/// <returns>representative of x.</returns>
public Node<T> FindSet(Node<T> node)
{
if (node != node.Parent)
{
node.Parent = FindSet(node.Parent);
}
return node.Parent;
}
/// <summary>
/// merge two sets.
/// </summary>
/// <param name="x">first set member.</param>
/// <param name="y">second set member.</param>
public void UnionSet(Node<T> x, Node<T> y)
{
Node<T> nx = FindSet(x);
Node<T> ny = FindSet(y);
if (nx == ny)
{
return;
}
if (nx.Rank > ny.Rank)
{
ny.Parent = nx;
}
else if (ny.Rank > nx.Rank)
{
nx.Parent = ny;
}
else
{
nx.Parent = ny;
ny.Rank++;
}
}
}
}