const std = @import("std");

pub const UnionFind = struct {
    // Single packed flat array of n i32 entries:
    //   data[x] < 0  => x is a root and -data[x] is the size of its set
    //   data[x] >= 0 => x is a non-root and data[x] is its parent index
    data: [*]i32,
    n: u32,
    num_sets: u32,
    allocator: std.mem.Allocator,

    pub fn init(allocator: std.mem.Allocator, n: u32) std.mem.Allocator.Error!UnionFind {
        const slice = try allocator.alloc(i32, n);
        @memset(slice, -1);
        return .{
            .data = slice.ptr,
            .n = n,
            .num_sets = n,
            .allocator = allocator,
        };
    }

    pub fn deinit(self: *UnionFind) void {
        self.allocator.free(self.data[0..self.n]);
        self.* = undefined;
    }

    // Full path compression for elements at depth >= 2.
    // Caller guarantees x -> n1 -> n2 with data[x] == n1 and data[n1] == n2.
    noinline fn findSlow(data: [*]i32, x: u32, n1: u32, n2: u32) u32 {
        const p2 = data[n2];
        if (p2 < 0) {
            data[x] = @bitCast(n2);
            return n2;
        }
        var root: u32 = @bitCast(p2);
        while (true) {
            const next = data[root];
            if (next < 0) break;
            root = @bitCast(next);
        }
        const root_i32: i32 = @bitCast(root);
        data[x] = root_i32;
        data[n1] = root_i32;
        var curr: u32 = @bitCast(p2);
        if (curr != root) {
            data[n2] = root_i32;
            while (true) {
                const next: u32 = @bitCast(data[curr]);
                if (next == root) break;
                data[curr] = root_i32;
                curr = next;
            }
        }
        return root;
    }

    pub inline fn find(self: *UnionFind, x: u32) u32 {
        const data = self.data;
        const p0 = data[x];
        const n1: u32 = if (p0 < 0) x else @bitCast(p0);
        const p1 = data[n1];
        if (p1 < 0) return n1;

        const n2: u32 = @bitCast(p1);
        const p2 = data[n2];
        if (p2 < 0) {
            data[x] = @bitCast(n2);
            return n2;
        }
        var root: u32 = @bitCast(p2);
        while (true) {
            const next = data[root];
            if (next < 0) break;
            root = @bitCast(next);
        }
        const root_i32: i32 = @bitCast(root);
        data[x] = root_i32;
        data[n1] = root_i32;
        var curr: u32 = @bitCast(p2);
        if (curr != root) {
            data[n2] = root_i32;
            while (true) {
                const next: u32 = @bitCast(data[curr]);
                if (next == root) break;
                data[curr] = root_i32;
                curr = next;
            }
        }
        return root;
    }

    pub inline fn unite(self: *UnionFind, a: u32, b: u32) bool {
        const data = self.data;
        const pa = data[a];
        const pb = data[b];
        const na: u32 = if (pa < 0) a else @bitCast(pa);
        const nb: u32 = if (pb < 0) b else @bitCast(pb);
        var sa = data[na];
        var sb = data[nb];
        var ra = na;
        var rb = nb;
        if ((sa & sb) >= 0) {
            @branchHint(.unlikely);
            if (sa >= 0) {
                ra = findSlow(data, a, na, @bitCast(sa));
                sa = data[ra];
            }
            if (sb >= 0) {
                rb = findSlow(data, b, nb, @bitCast(sb));
                sb = data[rb];
            }
        }
        if (ra == rb) return false;

        // Union by size (negative sizes: smaller value means larger set).
        // On a tie (sa == sb), ra remains the root.
        const swap = sa > sb;
        const big = if (swap) rb else ra;
        const small = if (swap) ra else rb;
        data[small] = @bitCast(big);
        data[big] = sa +% sb;
        self.num_sets -= 1;
        return true;
    }

    pub inline fn connected(self: *UnionFind, a: u32, b: u32) bool {
        const data = self.data;
        const pa = data[a];
        const pb = data[b];
        const na: u32 = if (pa < 0) a else @bitCast(pa);
        const nb: u32 = if (pb < 0) b else @bitCast(pb);
        const ga = data[na];
        const gb = data[nb];
        var ra = na;
        var rb = nb;
        if ((ga & gb) >= 0) {
            @branchHint(.unlikely);
            if (ga >= 0) ra = findSlow(data, a, na, @bitCast(ga));
            if (gb >= 0) rb = findSlow(data, b, nb, @bitCast(gb));
        }
        return ra == rb;
    }

    pub inline fn setSize(self: *UnionFind, x: u32) u32 {
        const data = self.data;
        const p0 = data[x];
        const n1: u32 = if (p0 < 0) x else @bitCast(p0);
        var p1 = data[n1];
        if (p1 >= 0) {
            @branchHint(.unlikely);
            const root = findSlow(data, x, n1, @bitCast(p1));
            p1 = data[root];
        }
        return @bitCast(-%p1);
    }

    pub inline fn sets(self: *const UnionFind) u32 {
        return self.num_sets;
    }

    pub inline fn len(self: *const UnionFind) u32 {
        return self.n;
    }

    pub inline fn parent(self: *const UnionFind, x: u32) u32 {
        const p = self.data[x];
        return if (p < 0) x else @bitCast(p);
    }
};
