// Package unionfind is a disjoint-set forest with union by size and path
// halving, stored in a single packed int32 array:
//
//	s[x] >= 0  ->  x is not a root; s[x] is its parent
//	s[x] <  0  ->  x is a root; -s[x] is the size of its set
package unionfind

import "unsafe"

type UnionFind struct {
	base unsafe.Pointer // &s[0], for bounds-check-free access
	s    []int32        // keeps the array alive
	n    uint32
	sets uint32
}

func New(n uint32) *UnionFind {
	s := make([]int32, n)
	// Fill here (untimed) so every page is touched before use.
	for i := range s {
		s[i] = -1
	}
	return &UnionFind{base: unsafe.Pointer(unsafe.SliceData(s)), s: s, n: n, sets: n}
}

// at returns a pointer to s[i] without a bounds check.
func at(base unsafe.Pointer, i uint32) *int32 {
	return (*int32)(unsafe.Add(base, uintptr(i)*4))
}

// Find returns the root of x, halving the path on the way.
func (u *UnionFind) Find(x uint32) uint32 {
	b := u.base
	v := *at(b, x)
	for v >= 0 {
		p := uint32(v)
		g := *at(b, p)
		if g < 0 {
			return p
		}
		*at(b, x) = g
		x = uint32(g)
		v = *at(b, x)
	}
	return x
}

// roots finds the roots of a and b in lockstep (so the memory accesses of
// the two searches overlap), halving both paths. It returns each root with
// its (negative) size entry.
func roots(b unsafe.Pointer, x, y uint32) (uint32, int32, uint32, int32) {
	vx := *at(b, x)
	vy := *at(b, y)
	for vx >= 0 && vy >= 0 {
		gx := *at(b, uint32(vx))
		gy := *at(b, uint32(vy))
		if gx < 0 {
			x, vx = uint32(vx), gx
		} else {
			*at(b, x) = gx
			x = uint32(gx)
			vx = *at(b, x)
		}
		if gy < 0 {
			y, vy = uint32(vy), gy
		} else {
			*at(b, y) = gy
			y = uint32(gy)
			vy = *at(b, y)
		}
	}
	for vx >= 0 {
		g := *at(b, uint32(vx))
		if g < 0 {
			x, vx = uint32(vx), g
			break
		}
		*at(b, x) = g
		x = uint32(g)
		vx = *at(b, x)
	}
	for vy >= 0 {
		g := *at(b, uint32(vy))
		if g < 0 {
			y, vy = uint32(vy), g
			break
		}
		*at(b, y) = g
		y = uint32(g)
		vy = *at(b, y)
	}
	return x, vx, y, vy
}

func (u *UnionFind) Union(a, c uint32) bool {
	b := u.base
	ra, sa, rc, sc := roots(b, a, c)
	if ra == rc {
		return false
	}
	// Sizes are negative: sa > sc means a's set is smaller.
	if sa > sc {
		ra, rc = rc, ra
	}
	*at(b, ra) = sa + sc
	*at(b, rc) = int32(ra)
	u.sets--
	return true
}

func (u *UnionFind) Connected(a, c uint32) bool {
	if a == c {
		return true
	}
	ra, _, rc, _ := roots(u.base, a, c)
	return ra == rc
}

func (u *UnionFind) SetSize(x uint32) uint32 {
	b := u.base
	v := *at(b, x)
	for v >= 0 {
		p := uint32(v)
		g := *at(b, p)
		if g < 0 {
			return uint32(-g)
		}
		*at(b, x) = g
		x = uint32(g)
		v = *at(b, x)
	}
	return uint32(-v)
}

func (u *UnionFind) Sets() uint32 { return u.sets }

func (u *UnionFind) Len() uint32 { return u.n }

func (u *UnionFind) Parent(x uint32) uint32 {
	v := u.s[x]
	if v < 0 {
		return x
	}
	return uint32(v)
}
