using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Disjoint-set forest packed into one int array: // _p[x] >= 0 : parent link of the non-root x // _p[x] < 0 : x is a root, and -_p[x] is the size of its set // Union by size, path halving in every root search. public sealed class UnionFind { private readonly int[] _p; private readonly int _n; private int _sets; public UnionFind(int n) { _n = n; _sets = n; if (n == 0) { _p = Array.Empty(); } else { _p = GC.AllocateUninitializedArray(n); _p.AsSpan().Fill(-1); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int Root(ref int b, int x) { int p = Unsafe.Add(ref b, x); if (p < 0) return x; for (;;) { int g = Unsafe.Add(ref b, p); if (g < 0) return p; // Path halving: link x to its grandparent and jump there. Unsafe.Add(ref b, x) = g; x = g; p = Unsafe.Add(ref b, x); if (p < 0) return x; } } public int Find(int x) { return Root(ref MemoryMarshal.GetArrayDataReference(_p), x); } public bool Union(int a, int b) { ref int d = ref MemoryMarshal.GetArrayDataReference(_p); int ra = Root(ref d, a); int rb = Root(ref d, b); if (ra == rb) return false; int sa = Unsafe.Add(ref d, ra); // -size of a's set int sb = Unsafe.Add(ref d, rb); if (sa > sb) { // a's set is smaller: hang ra below rb. Unsafe.Add(ref d, rb) = sa + sb; Unsafe.Add(ref d, ra) = rb; } else { Unsafe.Add(ref d, ra) = sa + sb; Unsafe.Add(ref d, rb) = ra; } _sets--; return true; } public bool Connected(int a, int b) { ref int d = ref MemoryMarshal.GetArrayDataReference(_p); return Root(ref d, a) == Root(ref d, b); } public int SetSize(int x) { ref int d = ref MemoryMarshal.GetArrayDataReference(_p); return -Unsafe.Add(ref d, Root(ref d, x)); } public int Sets() => _sets; public int Count => _n; public int Parent(int x) { int p = _p[x]; return p < 0 ? x : p; } }