#pragma once

#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <new>

// Disjoint-set forest in one packed array of 32-bit signed entries:
//   p[x] >= 0  : parent link of x (x is not a root)
//   p[x] <  0  : x is a root and -p[x] is the size of its set
// Union by size, path halving. Searches for two roots (unite/connected)
// advance both paths in lockstep so their cache misses overlap.
class UnionFind {
public:
    explicit UnionFind(std::uint32_t n) : n_(n), sets_(n) {
        std::size_t bytes = (std::size_t)(n ? n : 1) * sizeof(std::int32_t);
        bytes = (bytes + 127) & ~(std::size_t)127;
        p_ = static_cast<std::int32_t*>(std::aligned_alloc(128, bytes));
        if (!p_) throw std::bad_alloc();
        // Every element a root of size 1 (-1 = all bytes 0xFF). Touching the
        // memory here also takes the page faults outside the operations.
        std::memset(p_, 0xFF, bytes);
    }
    ~UnionFind() { std::free(p_); }
    UnionFind(const UnionFind&) = delete;
    UnionFind& operator=(const UnionFind&) = delete;

    __attribute__((always_inline)) std::uint32_t find(std::uint32_t x) {
        std::int32_t* const p = p_;
        for (;;) {
            std::int32_t px = p[x];
            if (px < 0) return x;
            std::int32_t gx = p[px];
            if (gx < 0) return (std::uint32_t)px;
            p[x] = gx;  // path halving: link x to its grandparent
            x = (std::uint32_t)gx;
        }
    }

    __attribute__((always_inline)) bool unite(std::uint32_t a, std::uint32_t b) {
        std::uint32_t ra, rb;
        if (!roots(a, b, ra, rb)) return false;
        std::int32_t* const p = p_;
        std::int32_t sa = p[ra], sb = p[rb];  // negated sizes
        if (sa > sb) {                        // set of ra is smaller
            p[ra] = (std::int32_t)rb;
            p[rb] = sa + sb;
        } else {
            p[rb] = (std::int32_t)ra;
            p[ra] = sa + sb;
        }
        --sets_;
        return true;
    }

    __attribute__((always_inline)) bool connected(std::uint32_t a, std::uint32_t b) {
        std::uint32_t ra, rb;
        return !roots(a, b, ra, rb);
    }

    __attribute__((always_inline)) std::uint32_t set_size(std::uint32_t x) {
        return (std::uint32_t)(-p_[find(x)]);
    }

    std::uint32_t sets() const { return sets_; }
    std::uint32_t len() const { return n_; }
    std::uint32_t parent(std::uint32_t x) const {
        std::int32_t px = p_[x];
        return px < 0 ? x : (std::uint32_t)px;
    }

private:
    // Searches for the roots of a and b together, halving both paths.
    // Returns false as soon as both searches meet (same set); otherwise
    // returns true with the two (distinct) roots in ra and rb.
    __attribute__((always_inline)) bool roots(std::uint32_t a, std::uint32_t b, std::uint32_t& ra,
                                              std::uint32_t& rb) {
        std::int32_t* const p = p_;
        for (;;) {
            if (a == b) return false;
            std::int32_t pa = p[a], pb = p[b];
            if (pa < 0) {
                rb = find(b);
                ra = a;
                return ra != rb;
            }
            if (pb < 0) {
                ra = find(a);
                rb = b;
                return ra != rb;
            }
            std::int32_t ga = p[pa], gb = p[pb];
            if (ga >= 0) {
                p[a] = ga;
                a = (std::uint32_t)ga;
            } else {
                a = (std::uint32_t)pa;
            }
            if (gb >= 0) {
                p[b] = gb;
                b = (std::uint32_t)gb;
            } else {
                b = (std::uint32_t)pb;
            }
        }
    }

    std::int32_t* p_;
    std::uint32_t n_;
    std::uint32_t sets_;
};
