"""Reproduce the rational bounds in Appendix B from the short-row table.""" from fractions import Fraction as F from functools import cache from math import ceil, floor from pathlib import Path TEST_GAPS = (8, 12, 16, 20, 24, 32, 40, 48, 64, 80, 96) GAPS = sorted({d for q in TEST_GAPS for d in range(1,q+1) if q%d == 0}) SHORT_GAPS = (1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,64) ENUM, LIMIT, HOLE_CAP = 192, 384, 20 PRICES = range(257) # quarter units def complete_rows(max_length=LIMIT): """Each word stores its even and odd traces and its parity orientation.""" counts = {q: [0, 0] for q in GAPS} prev = {0: (0,0,0), 1: (1,0,0)} shorter = [set(), set(prev)] enum_length = min(max_length, ENUM) for n in range(2, enum_length+1): mask = (1 << (n-1))-1 cur = {} for high, (evens, odds, flags) in prev.items(): shifted = (0,2,1)[flags] for bit in (0,1): w = 2*high + bit low = prev.get(w & mask) if low is None: continue orientation = shifted | low[2] # The only new reflected triple using both ends is (0,mid,n-1). if n%4 == 3: middle = (w >> (n//2)) & 1 if bit != middle or w >> (n-1) != middle: orientation |= 2 if middle else 1 even, odd = 2*odds+bit, evens if orientation != 3 and even in shorter[(n+1)//2] and odd in shorter[n//2]: cur[w] = (even,odd,orientation) for q in GAPS: starts = (1 << max(0,n-q))-1 counts[q].append(max(((w ^ (w>>q)) & starts).bit_count() for w in cur)) if n <= (enum_length+1)//2: shorter.append(set(cur)) prev = cur for q, row in counts.items(): for n in range(ENUM+1,max_length+1): row.append(min(row[q+j]+row[n-j] for j in range(1,ENUM-q+1))) print(f"Length {enum_length}: {len(prev)} complete-row words") return counts def row_bounds(complete, *, fair, table_path): units = 2 if fair else 1 direct = {} source = Path(table_path) for line in source.read_text().splitlines(): n,h,*values = map(int,line.split()) for q,value in zip(SHORT_GAPS, values, strict=True): direct[n,q,h] = value @cache def upper(n,q,h): if not h: return units*complete[q][n] pairs = max(0,n-q) best = direct.get((n,q,h), units*pairs) if not pairs or h >= HOLE_CAP or (q == 1 and not fair): return best # A crossing pair incident to the first hole has expected score one # in half units. Other crossing pairs cost at most two. split = max(units*(pairs-max(0,i-q)-max(0,n-i-1-q)+complete[q][i]) + upper(n-i-1,q,h-1) - (int(i>=q)+int(n-i-1>=q) if fair else 0) for i in range(n-h+1)) best = min(best,split) for p in (2,3,5): if q%p: continue # Distribute h holes among the p residue classes. budget = [0] for r in range(p): length = (n+p-1-r)//p budget = [ max(budget[t-j]+upper(length,q//p,j) for j in range(max(0,t-len(budget)+1),min(t,length)+1)) for t in range(min(h,len(budget)-1+length)+1) ] best = min(best,budget[h]) return best return upper def prices_and_rules(q, upper, units=1): table = {} for n in range(q,LIMIT+1): values = [(4//units)*upper(n,q,h) for h in range(min(n,HOLE_CAP)+1)] table[n] = [max(value-h*p for h,value in enumerate(values)) for p in PRICES] rules = [] for k in range(32,193,8): for cost in range(3,25): p = 4*cost slope = F(table[q+k][p],4*k) intercept = F(sum(table[q+j][p] for j in range(k)),2*k) - (k-1)*slope rate = cost*F(k+q,k) rules.append((q+k,rate,slope,intercept)) for n in range(q,LIMIT+1): caps = table[n] for minimum,rate,slope,intercept in rules: p = ceil(4*rate) if n >= minimum and p < len(caps): caps[p] = min(caps[p],floor(4*(slope*(n-q)+intercept))) for p in range(1,len(caps)): caps[p] = min(caps[p],caps[p-1]) return table,rules def tail_lines(q,rules,denom): # On 0 <= x <= q/LIMIT a line dominated at both ends can be dropped. lines = {(s+w/denom, v/q-s) for _,w,s,v in rules} last = None kept = [] for a,b in sorted(lines): right = a+b*F(q,LIMIT) if last is None or right < last: kept.append((a,b)) last = right return kept def window_bound(data, denom): cuts = sorted({F(i,384) for i in range(385)} | {F(q,n) for q in TEST_GAPS for n in range(q,LIMIT+1)}) tails = {q:tail_lines(q,rules,denom) for q,(_,rules) in data.items()} total = F() for lo,hi in zip(cuts,cuts[1:]): t = (lo+hi)/2 a,m = t.as_integer_ratio() best = 1-t for q,(table,_) in data.items(): n = q*m//a if n >= LIMIT: bound = min(u+v*t for u,v in tails[q]) else: left = (n+1)*a-q*m right = q*m-n*a numerator = min(denom*(left*x+right*y)+p*q*m for p,(x,y) in enumerate(zip(table[n],table[n+1]))) bound = F(numerator,4*denom*q*m) best = min(best,bound) total += 2*(hi-lo)*best return total def refine_sliding_rules(data, verbose=False): """One additional valid pass; input tables stay fixed throughout. Values are 4*A(c), and price denotes 4*c. For k starts use R=4*A(q+k,c), V=2*sum(4*A(q+j,c))-(k-1)*R. The row bound is [R*(n-q)+V]/(4*k)+c*(1+q/k)*h. At quarter prices >= c*(1+q/k), integrality permits rounding [R*(n-q)+V]/k down to an integer. """ result = {} for gap, (source, old_rules) in data.items(): limit = max(source) width = len(source[gap]) assert limit >= gap + 192 and width >= 33 table = {n: row.copy() for n, row in source.items()} rules = list(old_rules) prefixes = {} for price in range(8, 33): prefix = [0] for n in range(gap, gap + 192): prefix.append(prefix[-1] + source[n][price]) prefixes[price] = prefix for size in range(8, 193, 4): for price in range(8, 33): row_cost = source[gap + size][price] end_cost = 2 * prefixes[price][size] - (size - 1) * row_cost rate = F(price * (size + gap), 4 * size) rules.append((gap + size, rate, F(row_cost, 4 * size), F(end_cost, 4 * size))) charged_price = ceil(4 * rate) if charged_price >= width: continue for n in range(gap + size, limit + 1): value = (row_cost * (n - gap) + end_cost) // size table[n][charged_price] = min(table[n][charged_price], value) for row in table.values(): for price in range(1, width): row[price] = min(row[price], row[price - 1]) if verbose: lowered = sum(a < b for n in table for a, b in zip(table[n], source[n], strict=True)) print(f"Gap {gap}: {lowered} quarter-price entries improved.", flush=True) result[gap] = (table, rules) return result if __name__ == "__main__": complete = complete_rows() upper = row_bounds(complete, fair=True, table_path=Path(__file__).with_name("short_rows_fair_components.txt")) data = {q: prices_and_rules(q, upper, units=2) for q in TEST_GAPS} for b, rounded, threshold in ((66, 266592, F(259, 968)), (43, 332288, F(99593, 299538))): bound = F(ceil(10**6 * window_bound(data, b)), 10**6) assert bound == F(rounded, 10**6) and bound < threshold print(f"Missing fraction 1/{b}: {bound} < {threshold}")