26 using System.Collections.Generic;
32 public struct DisjointSetSet<T> : IEquatable<DisjointSetSet<T>>
34 public T Representative {
get;
private set; }
36 public DisjointSetSet(T representative)
39 Representative = representative;
47 public override bool Equals(
object obj)
63 public override int GetHashCode()
65 return Representative.GetHashCode();
68 public override string ToString()
70 return "[DisjointSetSet:" + Representative +
"]";
75 public interface IReadOnlyDisjointSet<T>
86 public interface IDisjointSet<T> : IReadOnlyDisjointSet<T>,
IClearable
93 public sealed
class DisjointSet<T> : IDisjointSet<T>
95 private readonly Dictionary<T, T> parent;
97 private readonly Dictionary<T, T> next;
99 private readonly Dictionary<T, T> last;
100 private readonly List<T> tmpList;
104 parent =
new Dictionary<T, T>();
105 next =
new Dictionary<T, T>();
106 last =
new Dictionary<T, T>();
107 tmpList =
new List<T>();
122 if (!parent.TryGetValue(element, out p))
124 foreach (var a
in tmpList) parent[a] = element;
130 tmpList.Add(element);
136 private T GetLast(T x)
139 if (last.TryGetValue(x, out y))
return y;
151 next[GetLast(y)] = x;
152 last[y] = GetLast(x);
163 yield
return element;
164 if (!next.TryGetValue(element, out element))
break;