/// <summary> /// Unites two disjoint sets given the root elements of the sets. /// </summary> /// <param name="xNode">The root of (the tree representing) the first set.</param> /// <param name="yNode">The root of (the tree representing) the second set.</param> /// <remarks><paramref name="xNode"/> and <paramref name="yNode"/> are assumed to /// correspond to elements of different sets.</remarks> private void Link(DisjointSetsNode <T> xNode, DisjointSetsNode <T> yNode) { DisjointSetsNode <T> parentNode, childNode; if (xNode.Rank > yNode.Rank) { childNode = yNode; parentNode = xNode; } else { childNode = xNode; parentNode = yNode; } childNode.Parent = parentNode; if (childNode.Rank == parentNode.Rank) { parentNode.Rank += 1; } // Swap nexts var tempNode = parentNode.Next; parentNode.Next = childNode.Next; childNode.Next = tempNode; }
public DisjointSetsNode(T x) { Element = x; Parent = null; Rank = 0; Next = this; }
/// <summary> /// Inserts a singleton into the collection of disjoint sets. /// </summary> /// <param name="x">The element of the singleton to insert.</param> /// <exception cref="ArgumentException"><paramref name="x"/> is already exists in the collection of disjoint sets.</exception> public void MakeSet(T x) { if (dict.ContainsKey(x)) { throw new ArgumentException($"The element {x} already exists in the collection of disjoint sets.", nameof(x)); } var node = new DisjointSetsNode <T>(x); dict[x] = node; NumberOfSets++; }