"""Block stacking (overhang) problem, closed form of the constraints; checked in exact rational arithmetic. Upstream (block_stacking_problem.ipynb) used a float tolerance of 100*eps on every constraint, which lets a submission exceed the true optimum H_n/2 by accumulated slack; here all constraints are exact (non-strict). """ from fractions import Fraction from run import Invalid, float_list def check(inst, ans): n = inst["n"] x = [Fraction(v) for v in float_list(ans.get("x"), n, "x")] xs = [Fraction(0)] + x # x_0 = 0 for i in range(n): if xs[i + 1] < xs[i]: raise Invalid(f"need x_{i} <= x_{i + 1}") tail = Fraction(0) for i in range(n - 1, -1, -1): # tail = x_{i+1} + ... + x_n tail += xs[i + 1] if tail > (n - i) * (xs[i] + Fraction(1, 2)): raise Invalid(f"stability constraint violated at i = {i}") return float(xs[n]), {}