"""Integer enclosures for the affinity of two fully merged schedules at the tested sizes."""
from functools import lru_cache
from math import isqrt
import json

UNIT = 1 << 96


def ceiling(n, d):
    return -(-n//d)


def enclosure(h, kind):
    m = isqrt(h)
    if h <= 4 or kind not in (0,1):
        raise ValueError("requires H>4 and a binary cell type")
    n = h*h
    if m*m == h:
        den, low_b, high_b = n*m, 1, 1
    else:
        # Grid enclosure of b=1/(N sqrt(H)), by integer squaring.
        den = UNIT
        low_b = isqrt(den**2 // (n*n*h))
        high_b = low_b + 1
    cell = ((1,1),(2,2)) if kind==0 else ((1,2),(1,2))

    @lru_cache(None)
    def weights(s, a, b):
        # P(d) numerators for d=0,1,2. Write them via first-step outcomes.
        den2 = den*den
        def p_bounds(x, y):
            # x bounds increasing factors, y bounds decreasing factors.
            return [(den-s*a*y)*(den-s*b*y),
                    s*a*x*(den-(s-1)*b*y) + (den-s*a*y)*s*b*x,
                    s*(s-1)*a*b*x*x]
        p_lo = p_bounds(low_b, high_b)
        p_hi = p_bounds(high_b, low_b)
        assert sum(p_lo) <= den2 <= sum(p_hi)
        u_lo = (den-a*high_b)*(den-b*high_b)
        u_hi = (den-a*low_b)*(den-b*low_b)
        def power(j):
            lo=hi=UNIT
            l=u_lo*UNIT//den2
            r=ceiling(u_hi*UNIT,den2)
            while j:
                if j&1:
                    lo,hi=lo*l//UNIT,ceiling(hi*r,UNIT)
                l,r=l*l//UNIT,ceiling(r*r,UNIT)
                j//=2
            return lo,hi
        result=[]
        for d, factor in enumerate((1,s,s*(s-1)//2)):
            if d>s:
                break
            lo,hi=power(s-d)
            num_lo = p_lo[d]*factor*(den2-u_hi)**d
            num_hi = p_hi[d]*factor*(den2-u_lo)**d
            div = den2**(d+1)
            low = isqrt(lo*num_lo*UNIT//div)
            high = isqrt(hi*num_hi*UNIT//div)+1
            result.append((low,high))
        return result

    # Backward continuation affinity after the last observation is one.
    future = [(UNIT,UNIT)]*(min(n,4*h)+1)
    for t in reversed(range(2*h)):
        a,b=cell[t%2]
        curr=[]
        for deaths in range(min(n,2*t)+1):
            lo=hi=0
            for d,(l,r) in enumerate(weights(n-deaths,a,b)):
                fl,fr=future[deaths+d]
                lo+=l*fl
                hi+=r*fr
            curr.append((lo//UNIT,ceiling(hi,UNIT)))
        future=curr
    return future[0]


def run():
    records=[]
    for h in (9,111,112,144):
        pair=[enclosure(h,kind) for kind in (0,1)]
        assert pair[0][1]<pair[1][0] if h in (9,111) else pair[1][1]<pair[0][0]
        records.append(dict(H=h,numerator_bounds=pair,smaller_affinity_type=0 if h in (9,111) else 1))
    return dict(denominator=UNIT,fully_merged=records)


if __name__=="__main__":
    print(json.dumps(run(),indent=2))
