"""Fixed-point bounds for the two signed principal contributions.""" from bisect import bisect_right SCALE = 10**16 def mean(threshold, bins, rows, upper): def divide(value, divisor): return -(-value // divisor) if upper else value // divisor def scale(left, right): return divide(left * right, SCALE) costs, caps, weights = [], [], [] low, high = [0], [0] for prime, lower_cost, upper_cost, *quantiles in rows: limits = [threshold - 3 * q for q in quantiles[(0 if upper else 1)::2]] if limits[0] < 0: break costs.append(lower_cost if upper else upper_cost) caps.append(limits) weights.append(divide(SCALE, prime - 1)) low.append(low[-1] + SCALE // (prime - 1)) high.append(high[-1] - (-SCALE // (prime - 1))) assert costs == sorted(costs) cache = {} size = len(costs) def even(budget, start): if budget < 0: return 0 if start + 1 >= size or costs[start] + costs[start + 1] > budget: return SCALE key = (budget, start) if key in cache: return cache[key] value = SCALE for j in range(start + 1, size): if costs[start] + costs[j] > budget: break end = bisect_right(costs, budget - costs[j], start, j) mass = high[end] - low[start] if upper else low[end] - high[start] valid = [z for z in caps[j] if z >= 0] value += scale(weights[j], divide(max(0, mass) * len(valid), bins)) if j + 2 >= size: continue needed = costs[j + 1] + costs[j + 2] if caps[j][0] < needed: continue for t in range(start, end): remaining = budget - costs[t] - costs[j] if remaining < needed: break extra = sum(even(min(z, remaining), j + 1) - SCALE for z in valid) value += scale(scale(weights[t], weights[j]), divide(extra, bins)) if start < 400: cache[key] = value return value total = SCALE if upper else 0 for j, limits in enumerate(caps): term = scale(weights[j], divide(sum(even(z, j + 1) for z in limits), bins)) total += scale(high[j], term) if upper else term return total def evaluate(hi, lo, bins, path): rows = [tuple(map(int, line.split())) for line in path.read_text().splitlines()] assert bins > 0 and all(len(row) == 3 + 2 * bins for row in rows) even = mean(hi, bins, rows, True) odd = mean(lo, bins, rows, False) return even, odd, -(-(27 * (even - odd)) // 80), SCALE