import json,pathlib,sys,re,itertools,functools
from fractions import Fraction as F
PACK='grade7-three-view-stacks'
SUBTYPES=['s72-height-views', 's72-view-range']
REQ={
's71-object-symbols':['labels','endpointCount','extensionDirections','singlePointConfirmed'],
's71-angle-symbols':['vertex','armA','armB','nonstraightAngleConfirmed'],
's71-triangle-symbols':['vertices','triangleConfirmed'],
's72-height-views':['heights','bottomStackedConfirmed','sameUnitCubesConfirmed','orientationConfirmed'],
's72-view-range':['frontHeights','leftHeights','topOccupied','bottomStackedConfirmed','sameUnitCubesConfirmed','orientationConfirmed'],
's73-perpendicular-symbol':['lineA','lineB','angleDegrees','intersectionConfirmed'],
's73-perpendicular-bisector':['segmentLength','firstPart','secondPart','intersectionAngle','intersectionOnSegmentConfirmed','unit'],
's73-point-line-distance':['perpendicularLength','perpendicularFootConfirmed','otherSegments','unit'],
's74-corresponding-measures':['measureKind','originalMeasure','originalLabel','pairedLabel','correspondenceConfirmed','unit'],
's74-axis-point-relations':['pointOnAxis','pointToAxis','pairConfirmed','unit'],
's75-basic-axis-count':['shape','specialCase','axisQuery','nondegenerateConfirmed'],
's75-shape-equal-measures':['relationCase','knownValue','figureConfirmed','roleConfirmed','unit'],
's75-regular-axis-types':['sides','axisQuery','regularConvexConfirmed']}
FLAGS={'singlePointConfirmed','nonstraightAngleConfirmed','triangleConfirmed','bottomStackedConfirmed','sameUnitCubesConfirmed','orientationConfirmed','intersectionConfirmed','intersectionOnSegmentConfirmed','perpendicularFootConfirmed','correspondenceConfirmed','pointOnAxis','pairConfirmed','nondegenerateConfirmed','figureConfirmed','roleConfirmed','regularConvexConfirmed'}
NUMERIC={'endpointCount','extensionDirections','angleDegrees','axisAngle','midpointDistance','distance','value','eachHalf','pairDistance','axisCount','vertexToVertexAxes','vertexToEdgeAxes','edgeToEdgeAxes','requestedAxisCount','cubeCount','minCubeCount','maxCubeCount','configurationCount'}
def num(v,answer=False):
 if type(v)is int:
  if abs(v)>10**18:raise ValueError('數字過大')
  q=F(v)
 elif type(v)is str and len(v)<=64 and re.fullmatch(r'-?[0-9]{1,18}(?:/[1-9][0-9]{0,17}|\.[0-9]{1,12})?',v,re.ASCII):q=F(v)
 else:raise ValueError('只接受有界整數、小數或分數文字')
 if not answer and (abs(q)>10**6 or q.denominator>10000):raise ValueError('超出原量有限域')
 return q
def nstr(v):return str(v)
def nat(v,lo,hi):
 if type(v)is not int or not lo<=v<=hi:raise ValueError('整數或範圍不符')
 return v
def enum(v,allowed):
 if type(v)is not str or len(v)>80 or v not in allowed:raise ValueError('種類不符')
 return v
def label(v):
 if type(v)is not str or not re.fullmatch('[A-Z]',v):raise ValueError('點名須單一大寫英文字母')
 return v
def missing(v,depth=0):
 if v is None:return True
 # Legal arrays have at most two list layers (matrix -> row -> cell).
 # Deeper malformed structures fall through to the existing typed guards.
 if depth<2 and type(v)is list and len(v)<=27:return any(missing(x,depth+1)for x in v)
 return False
def unit(v):return enum(v,['cm','m'])
def positive(v):
 x=num(v)
 if x<=0:raise ValueError('須為正量')
 return x
def grid(v,hi):
 if type(v)is not list or not 1<=len(v)<=3 or any(type(row)is not list or not 1<=len(row)<=3 for row in v)or len({len(row)for row in v})!=1:raise ValueError('只限1到3列欄規則表')
 return [[nat(x,0,hi)for x in row]for row in v]
@functools.lru_cache(maxsize=512)
def enumerate_stacks(front,left,top):
 nr,nc=len(left),len(front);positions=[(i,j)for i in range(nr)for j in range(nc)if top[i][j]];choices=[range(1,min(left[i],front[j])+1)for i,j in positions];counts=[]
 for heights in itertools.product(*choices):
  g=[[0]*nc for _ in range(nr)]
  for (i,j),h in zip(positions,heights):g[i][j]=h
  if tuple(max(g[i][j]for i in range(nr))for j in range(nc))!=front:continue
  if tuple(max(row)for row in g)!=left:continue
  counts.append(sum(heights))
 return tuple(sorted(counts))
class Need(Exception):pass

def compute(s,r):
 for k in FLAGS&set(r):
  if type(r[k])is not bool:raise ValueError('確認旗標需真假')
 if any(not r[k]for k in FLAGS&set(r)if k not in ['singlePointConfirmed','pointOnAxis']):raise Need('先核外部幾何條件')
 if s=='s71-object-symbols':
  a=r['labels'];e=nat(r['endpointCount'],0,2);x=nat(r['extensionDirections'],0,2)
  if type(a)is not list or not 1<=len(a)<=2:raise ValueError('點名表不符')
  a=[label(z)for z in a]
  if len(set(a))!=len(a):raise ValueError('兩相異點不能同名')
  if r['singlePointConfirmed']:
   if (e,x,len(a))!=(0,0,1):raise Need('單點紀錄與端點延伸矛盾')
   kind='point';notation=a[0]
  else:
   kind={(0,2):'line',(1,1):'ray',(2,0):'segment'}.get((e,x))
   if kind is None or len(a)!=2:raise Need('端點與延伸條件需核對')
   notation={'line':'直線','ray':'射線','segment':'線段'}[kind]+''.join(a)
  formal=a[0]if kind=='point'else {'line':r'\overleftrightarrow','segment':r'\overline','ray':r'\overrightarrow'}[kind]+'{'+''.join(a)+'}'
  return dict(objectKind=kind,notation=notation,formalSymbol=formal,endpointCount=e,extensionDirections=x)
 if s=='s71-angle-symbols':
  v,a,b=[label(r[k])for k in ['vertex','armA','armB']]
  if len({v,a,b})!=3:raise ValueError('角三點須相異')
  return dict(vertex=v,notation='∠'+a+v+b)
 if s=='s71-triangle-symbols':
  a=r['vertices']
  if type(a)is not list or len(a)!=3:raise ValueError('三頂點')
  a=[label(v)for v in a]
  if len(set(a))!=3:raise ValueError('三頂點須相異')
  return dict(notation='△'+''.join(a),vertexSet=sorted(a))
 if s=='s72-height-views':
  h=grid(r['heights'],3)
  if not any(any(row)for row in h):raise Need('空配置不是本題已確認立體')
  return dict(frontHeights=[max(row[j]for row in h)for j in range(len(h[0]))],leftHeights=[max(row)for row in h],topOccupied=[[int(v>0)for v in row]for row in h],cubeCount=sum(map(sum,h)))
 if s=='s72-view-range':
  front,left=r['frontHeights'],r['leftHeights'];top=grid(r['topOccupied'],1)
  if type(front)is not list or type(left)is not list or not 1<=len(front)<=3 or not 1<=len(left)<=3:raise ValueError('視圖列欄不符')
  front=[nat(x,0,3)for x in front];left=[nat(x,0,3)for x in left]
  if len(top)!=len(left)or len(top[0])!=len(front):raise Need('三視圖同方向列欄不一致')
  if not any(front)or not any(left):raise Need('空視圖或相互矛盾，回查原資料')
  counts=enumerate_stacks(tuple(front),tuple(left),tuple(tuple(row)for row in top))
  if not counts:raise Need('沒有符合三份已確認紀錄的自底堆疊，回查原視圖與額外堆疊條件')
  return dict(configurationCount=len(counts),possibleCubeCounts=sorted(set(counts)),minCubeCount=min(counts),maxCubeCount=max(counts),cubeCountUnique=min(counts)==max(counts))
 if s=='s73-perpendicular-symbol':
  a=label(r['lineA']);b=label(r['lineB']);ang=num(r['angleDegrees'])
  if a==b or not 0<ang<180:raise ValueError('不同相交直線與非平退角')
  return dict(isPerpendicular=ang==90,notation=a+('⊥'if ang==90 else'不垂直')+b)
 if s=='s73-perpendicular-bisector':
  length=positive(r['segmentLength']);a=num(r['firstPart']);b=num(r['secondPart']);angle=num(r['intersectionAngle']);u=unit(r['unit'])
  if a<0 or b<0 or not 0<angle<180:raise ValueError('分段或交角不符')
  if a+b!=length:raise Need('兩分段和不等原線段，先核原量')
  mid=a==b;perp=angle==90
  return dict(passesMidpoint=mid,isPerpendicular=perp,isPerpendicularBisector=mid and perp,midpointDistance=nstr(length/2),unit=u)
 if s=='s73-point-line-distance':
  d=num(r['perpendicularLength']);other=r['otherSegments'];u=unit(r['unit'])
  if d<0 or type(other)is not list or len(other)>6:raise ValueError('距離或候選紀錄不符')
  other=[num(z)for z in other]
  if any(z<d for z in other):raise Need('已知垂足段卻有更短到直線段，原紀錄矛盾先核')
  return dict(distance=nstr(d),unit=u)
 if s=='s74-corresponding-measures':
  kind=enum(r['measureKind'],['segment','angle']);v=positive(r['originalMeasure']);a=r['originalLabel'];b=r['pairedLabel'];u=enum(r['unit'],['cm','m','degree']);n=2 if kind=='segment'else 3
  if any(type(t)is not str or len(t)!=n or len(set(t))!=n or any(not re.fullmatch('[A-Z]',x)for x in t)for t in [a,b]):raise ValueError('原與對應角色點名不符')
  if (kind=='angle'and(not v<180 or u!='degree'))or(kind=='segment'and u=='degree'):raise Need('量的角色與單位需一致')
  return dict(value=nstr(v),unit=u,relation='對稱線段等長'if kind=='segment'else'對稱角相等')
 if s=='s74-axis-point-relations':
  d=num(r['pointToAxis']);u=unit(r['unit']);on=r['pointOnAxis']
  if d<0:raise ValueError('距離不負')
  if on!=(d==0):raise Need('軸上紀錄與距離矛盾')
  return dict(eachHalf=nstr(d),pairDistance=nstr(d+d),pairCoincides=on,axisAngle=None if on else 90,unit=u)
 if s=='s75-basic-axis-count':
  shape=enum(r['shape'],['isosceles-triangle','square','rhombus','kite']);special=r['specialCase']
  choices={'isosceles-triangle':{'equilateral':3,'non-equilateral':1},'square':{'square':4},'rhombus':{'square':4,'non-square':2},'kite':{'proper-kite':1,'rhombus-nonsquare':2,'square':4}}
  special=enum(special,choices[shape]);n=choices[shape][special]
  desc=('三個頂點各到對邊中點'if shape=='isosceles-triangle'and n==3 else'頂角到不等邊中點'if shape=='isosceles-triangle'else'兩條對角線與兩組對邊中點連線'if n==4 else'兩條對角線'if n==2 else'兩對等長鄰邊各自相接的頂點連線')
  query=enum(r['axisQuery'],['all','diagonal','opposite-midpoints','vertex-midpoint'])
  istri=shape=='isosceles-triangle'
  selected=n if query=='all'else n if istri and query=='vertex-midpoint'else 0 if istri else 2 if query=='diagonal'and n>=2 else 1 if query=='diagonal'and n==1 else 2 if query=='opposite-midpoints'and n==4 else 0
  return dict(axisCount=n,requestedAxisCount=selected,axisDescription=desc)
 if s=='s75-shape-equal-measures':
  case=enum(r['relationCase'],['isosceles-equal-sides','rhombus-opposite-angles','kite-symmetric-angles','square-diagonal-halves']);v=positive(r['knownValue']);u=enum(r['unit'],['cm','m','degree'])
  angular='angles'in case
  if angular!=(u=='degree')or angular and v>=180:raise Need('角與長度單位/範圍要核對')
  ans=v/2 if case=='square-diagonal-halves'else v
  why={'isosceles-equal-sides':'等腰三角形兩腰相等','rhombus-opposite-angles':'菱形對角相等','kite-symmetric-angles':'箏形對稱軸兩側相對應角相等','square-diagonal-halves':'正方形兩對角線互相平分'}[case]
  return dict(value=nstr(ans),unit=u,relation=why)
 if s=='s75-regular-axis-types':
  n=nat(r['sides'],3,12);query=enum(r['axisQuery'],['all','vertex-vertex','vertex-edge','edge-edge']);vv=n//2 if n%2==0 else 0;ve=n if n%2 else 0;ee=vv
  return dict(axisCount=n,vertexToVertexAxes=vv,vertexToEdgeAxes=ve,edgeToEdgeAxes=ee,requestedAxisCount={'all':n,'vertex-vertex':vv,'vertex-edge':ve,'edge-edge':ee}[query])
 raise ValueError('unknown method')
def equivalent(p,a,s):
 if type(p)is not dict or set(p)!=set(a):return False
 try:
  for k,v in a.items():
   if k=='formalSymbol':
    if type(p[k])is not str:return False
    valid={v}
    if a['objectKind']in ['line','segment']:valid.add(v[:-3]+v[-3:-1][::-1]+v[-1])
    if p[k]not in valid:return False
   elif k=='notation':
    if type(p[k])is not str:return False
    valid={v}
    if s=='s71-object-symbols'and a['objectKind']in ['line','segment']:valid.add(v[:-2]+v[-2:][::-1])
    if s=='s71-angle-symbols':valid.add(v[0]+v[1:][::-1])
    if s=='s71-triangle-symbols':valid={'△'+''.join(t)for t in itertools.permutations(a['vertexSet'])}
    if s=='s73-perpendicular-symbol':valid.add(v[-1]+v[1:-1]+v[0])
    if p[k]not in valid:return False
   elif type(v)is bool:
    if type(p[k])is not bool or p[k]!=v:return False
   elif v is None:
    if p[k]is not None:return False
   elif k in NUMERIC:
    if num(p[k],True)!=num(v,True):return False
   elif k=='possibleCubeCounts':
    if type(p[k])is not list or len(p[k])!=len(v)or sorted(num(z,True)for z in p[k])!=list(map(F,v)):return False
   elif k in ['frontHeights','leftHeights']:
    if type(p[k])is not list or len(p[k])!=len(v)or any(num(x,True)!=y for x,y in zip(p[k],v)):return False
   elif k=='topOccupied':
    if type(p[k])is not list or len(p[k])!=len(v):return False
    if any(type(x)is not list or len(x)!=len(y)or any(num(xx,True)!=yy for xx,yy in zip(x,y))for x,y in zip(p[k],v)):return False
   elif k=='vertexSet':
    if type(p[k])is not list or len(p[k])!=3 or any(type(z)is not str for z in p[k])or sorted(p[k])!=v:return False
   elif type(p[k])is not type(v)or p[k]!=v:return False
  return True
 except(ValueError,TypeError,KeyError,OverflowError,ZeroDivisionError):return False
def evaluate(s,r):
 def out(d,a=None,why=''):return dict(decision=d,answer=a,reason=why)
 if type(s)is not str or s not in SUBTYPES or type(r)is not dict:return out('block',why='不在此有限文字方法')
 req=REQ[s]+['factsConfirmed','task']
 if any(k not in r or missing(r[k])for k in req):return out('confirm',why='先補原題缺量/角色/原觀察，不猜圖')
 if set(r)-set(req)-{'proposal'}:return out('block',why='未定義欄位')
 if type(r['factsConfirmed'])is not bool:return out('block',why='確認狀態須真假')
 if not r['factsConfirmed']:return out('confirm',why='原條件尚未確認')
 if type(r['task'])is not str or r['task']not in ['solve','check_proposal']:return out('block',why='任務不符')
 try:a=compute(s,r)
 except Need as e:return out('confirm',why=str(e))
 except(ValueError,TypeError,KeyError,OverflowError,ZeroDivisionError):return out('block',why='格式/有限方法範圍不符，不表示合法題在別的方法無解')
 if r['task']=='check_proposal':
  if r.get('proposal')is None:return out('confirm',a,'先補要核對的說法，保留原題正解')
  if not equivalent(r['proposal'],a,s):return out('reject',a,'只指出錯提案，保留原題正解與外部觀察限制')
 return out('pass',a,'僅核已確認文字幾何條件，不驗圖像、實物或學生能力')
# Original height methods retain their original globals and exact behavior.
_height_evaluate = evaluate
import json as _voxel_json, sys as _voxel_sys, pathlib as _voxel_pathlib, itertools as _voxel_itertools, re as _voxel_re
from fractions import Fraction as _voxel_Fraction
_voxel_SUBTYPES = ('s72-voxel-views', 's72-general-view-solutions')
_voxel_ORIENTATION = 'front:+y;top:-z;left:+x'
_voxel_COMMON = ('dimensions', 'orientation', 'indexingConfirmed', 'sameUnitCubesConfirmed', 'officialNoHollowRequirementConfirmed', 'noAdditionalShapeRestrictionsConfirmed', 'cavityConventionConfirmed', 'task')
_voxel_REQ = {_voxel_SUBTYPES[0]: _voxel_COMMON + ('voxels', 'configurationNoHollowExternallyConfirmed'), _voxel_SUBTYPES[1]: _voxel_COMMON + ('front', 'top', 'left')}

class _voxel_Guard(Exception):
    pass

class _voxel_Missing(Exception):
    pass

def _voxel_bounded(v):
    todo = [(v, 0)]
    nodes = 0
    while todo:
        (x, d) = todo.pop()
        nodes += 1
        if d > 7 or nodes > 1500:
            raise _voxel_Guard('結構超出有界文字資料')
        if type(x) is dict:
            if len(x) > 32 or any((type(k) is not str or len(k) > 80 for k in x)):
                raise _voxel_Guard('欄位不符')
            todo.extend(((z, d + 1) for z in x.values()))
        elif type(x) is list:
            if len(x) > 64:
                raise _voxel_Guard('列表過長')
            todo.extend(((z, d + 1) for z in x))
        elif type(x) is str:
            if len(x) > 160:
                raise _voxel_Guard('文字過長')
        elif type(x) is int:
            if x.bit_length() > 40:
                raise _voxel_Guard('整數過大')
        elif x is not None and type(x) is not bool:
            raise _voxel_Guard('只用JSON整數與明確文字')

def _voxel_missing(v):
    todo = [(v, 0)]
    n = 0
    while todo and n < 1500:
        (x, d) = todo.pop()
        n += 1
        if x is None:
            return True
        if d < 5 and type(x) in (dict, list) and (len(x) <= 64):
            todo.extend(((z, d + 1) for z in (x.values() if type(x) is dict else x)))
    return False

def _voxel_integer(x, lo, hi):
    if type(x) is not int or not lo <= x <= hi:
        raise _voxel_Guard('整數超出本型範圍')
    return x

def _voxel_dims(v):
    if type(v) is not list or len(v) != 3:
        raise _voxel_Guard('需完整長寬高格數')
    return tuple((_voxel_integer(x, 1, 3) for x in v))

def _voxel_cells(v, dim):
    if type(v) is not list or not 1 <= len(v) <= 27:
        raise _voxel_Guard('非空配置需1到27格，不把空格盤當立體')
    out = []
    for xyz in v:
        if type(xyz) is not list or len(xyz) != 3:
            raise _voxel_Guard('每格須三個已確認座標')
        out.append(tuple((_voxel_integer(x, 0, n - 1) for (x, n) in zip(xyz, dim))))
    if len(set(out)) != len(out):
        raise _voxel_Guard('同一格不可重複計數')
    return set(out)

def _voxel_grid(v, rows, cols):
    if type(v) is not list or len(v) != rows:
        raise _voxel_Guard('視圖列數不符')
    for row in v:
        if type(row) is not list or len(row) != cols:
            raise _voxel_Guard('視圖欄數不符')
        for x in row:
            _voxel_integer(x, 0, 1)
    return v

def _voxel_projections(v, dim):
    (nx, ny, nz) = dim
    return {'front': [[int(any(((x, y, z) in v for y in range(ny)))) for x in range(nx)] for z in range(nz)], 'top': [[int(any(((x, y, z) in v for z in range(nz)))) for x in range(nx)] for y in range(ny)], 'left': [[int(any(((x, y, z) in v for x in range(nx)))) for y in range(ny)] for z in range(nz)]}

def _voxel_cavity6(v, dim):
    return dim == (3, 3, 3) and (1, 1, 1) not in v and ({(0, 1, 1), (2, 1, 1), (1, 0, 1), (1, 2, 1), (1, 1, 0), (1, 1, 2)} <= v)

def _voxel_layer_choices(front, left, top):
    (ny, nx) = (len(top), len(top[0]))
    allowed = sum((top[y][x] << y * nx + x for y in range(ny) for x in range(nx)))
    out = []
    for mask in range(1 << nx * ny):
        if mask & ~allowed:
            continue
        if any((bool(mask & sum((1 << y * nx + x for y in range(ny)))) != bool(front[x]) for x in range(nx))):
            continue
        if any((bool(mask & (1 << nx) - 1 << y * nx) != bool(left[y]) for y in range(ny))):
            continue
        out.append(mask)
    return out

def _voxel_decode(mask, dim):
    (nx, ny, nz) = dim
    return [[x, y, z] for z in range(nz) for y in range(ny) for x in range(nx) if mask & 1 << z * nx * ny + y * nx + x]

def _voxel_inverse(front, top, left, dim):
    (nx, ny, nz) = dim
    target = sum((top[y][x] << y * nx + x for y in range(ny) for x in range(nx)))
    full = dim == (3, 3, 3)
    dp = {(0, 0, full): (1, [0])}
    transitions = 0
    for z in range(nz):
        choices = _voxel_layer_choices(front[z], left[z], top)
        nxt = {}
        for ((cov, n, possible_cavity), (count, witnesses)) in dp.items():
            for v in choices:
                transitions += 1
                if transitions > 20000000:
                    raise _voxel_Guard('安全計算預算用盡，未完成搜尋；不回傳唯一/完整結果')
                required = (bool(v & 1 << 4) if z in (0, 2) else not bool(v & 1 << 4) and v & 170 == 170) if full else False
                key = (cov | v, n + bin(v).count('1'), possible_cavity and required)
                (oldcount, oldw) = nxt.get(key, (0, []))
                examples = oldw + [w | v << z * nx * ny for w in witnesses]
                nxt[key] = (oldcount + count, sorted(set(examples))[:2])
        dp = nxt
    hist = {}
    examples = {}
    for ((cov, n, bad), (count, w)) in dp.items():
        if cov == target and n > 0 and (not bad):
            hist[n] = hist.get(n, 0) + count
            examples[n] = sorted(set(examples.get(n, []) + w))[:2]
    total = sum(hist.values())
    lo = min(hist) if hist else None
    hi = max(hist) if hist else None
    witness = []
    if total:
        witness = [examples[lo][0]]
        if total > 1:
            witness.append(examples[hi][0] if hi != lo else examples[lo][1])
    return {'status': 'no-compatible-nonempty-configuration' if not total else 'unique' if total == 1 else 'multiple', 'complete': True, 'configurationCount': total, 'cubeCountHistogram': [{'cubes': k, 'configurations': hist[k]} for k in sorted(hist)], 'minCubes': lo, 'maxCubes': hi, 'uniqueConfiguration': total == 1, 'witnesses': [_voxel_decode(w, dim) for w in witness], 'witnessesAreAllConfigurations': len(witness) == total, 'solutionSetRepresentation': 'exact-projection-rays+explicit-face6-no-cavity+nonempty', 'physicalVerified': False}

def _voxel_solve(s, r):
    dim = _voxel_dims(r['dimensions'])
    if type(r['orientation']) is not str or r['orientation'] != _voxel_ORIENTATION:
        raise _voxel_Missing('先確認前/上/左視與列欄方向，不能猜紙上鏡射')
    for k in ('indexingConfirmed', 'sameUnitCubesConfirmed', 'officialNoHollowRequirementConfirmed', 'noAdditionalShapeRestrictionsConfirmed'):
        if type(r[k]) is not bool:
            raise _voxel_Guard('確認欄須布林')
        if not r[k]:
            raise _voxel_Missing('先核原題方向、單位、不得中空要求或是否另有連通/接地等限制；有額外限制另轉方法')
    if type(r['cavityConventionConfirmed']) is not bool:
        raise _voxel_Guard('數位規則確認須布林')
    if s == _voxel_SUBTYPES[0]:
        if type(r['configurationNoHollowExternallyConfirmed']) is not bool:
            raise _voxel_Guard('外部確認須布林')
        if not r['configurationNoHollowExternallyConfirmed']:
            raise _voxel_Missing('尚未外部確認此配置符合原題不得中空要求')
        v = _voxel_cells(r['voxels'], dim)
        hole = _voxel_cavity6(v, dim)
        if hole:
            raise _voxel_Missing('數位檢查發現封閉空格，需外部釐清原題不得中空與此紀錄；不自行認定官方數位定義或合法性')
        return dict(_voxel_projections(v, dim), totalCubes=len(v), hasFace6EnclosedEmpty=hole, officialNoHollowVerification='external-only-not-official-definition-proof', physicalVerified=False)
    if not r['cavityConventionConfirmed']:
        raise _voxel_Missing('逆解需先確認題目採六面封閉空腔數位規則；不把它默認為官方定義')
    (nx, ny, nz) = dim
    front = _voxel_grid(r['front'], nz, nx)
    top = _voxel_grid(r['top'], ny, nx)
    left = _voxel_grid(r['left'], nz, ny)
    return _voxel_inverse(front, top, left, dim)

def _voxel_answer_integer(x):
    if type(x) is int:
        return _voxel_integer(x, 0, 1 << 27)
    if type(x) is not str or len(x) > 32 or _voxel_re.fullmatch('[0-9]{1,10}(?:/[1-9][0-9]{0,9})?', x) is None:
        raise _voxel_Guard('答案數量須有界整數或等值分數')
    q = _voxel_Fraction(x)
    if q.denominator != 1:
        raise _voxel_Guard('格數不能為非整數')
    return _voxel_integer(q.numerator, 0, 1 << 27)

def _voxel_equal(p, a, s, r):
    if type(p) is not dict or set(p) != set(a):
        return False
    try:
        _voxel_bounded(p)
        for (k, v) in a.items():
            if k in ('witnesses', 'cubeCountHistogram'):
                continue
            if type(v) is bool:
                if type(p[k]) is not bool or p[k] != v:
                    return False
            elif v is None:
                if p[k] is not None:
                    return False
            elif type(v) is int:
                if _voxel_answer_integer(p[k]) != v:
                    return False
            elif type(v) is list:
                if type(p[k]) is not list or len(p[k]) != len(v):
                    return False
                for (x, y) in zip(p[k], v):
                    if type(x) is not list or len(x) != len(y) or any((_voxel_answer_integer(xx) != yy for (xx, yy) in zip(x, y))):
                        return False
            elif type(p[k]) is not str or p[k] != v:
                return False
        if s == _voxel_SUBTYPES[1]:
            if type(p['cubeCountHistogram']) is not list:
                return False
            hs = []
            for z in p['cubeCountHistogram']:
                if type(z) is not dict or set(z) != {'cubes', 'configurations'}:
                    return False
                hs.append((_voxel_answer_integer(z['cubes']), _voxel_answer_integer(z['configurations'])))
            if len(set(hs)) != len(hs) or sorted(hs) != [(z['cubes'], z['configurations']) for z in a['cubeCountHistogram']]:
                return False
            if type(p['witnesses']) is not list or len(p['witnesses']) != len(a['witnesses']):
                return False
            seen = set()
            dim = _voxel_dims(r['dimensions'])
            for w in p['witnesses']:
                v = _voxel_cells(w, dim)
                key = frozenset(v)
                if key in seen or _voxel_cavity6(v, dim) or _voxel_projections(v, dim) != {k: r[k] for k in ('front', 'top', 'left')}:
                    return False
                seen.add(key)
        return True
    except (_voxel_Guard, ValueError, TypeError, KeyError, OverflowError, ZeroDivisionError):
        return False

def _voxel_evaluate(subtype_id, input_data):
    try:
        if type(subtype_id) is not str or subtype_id not in _voxel_SUBTYPES or type(input_data) is not dict:
            raise _voxel_Guard('非本有限方法')
        r = input_data
        _voxel_bounded(r)
        if any((k not in r for k in _voxel_REQ[subtype_id])) or _voxel_missing({k: r.get(k) for k in _voxel_REQ[subtype_id]}):
            raise _voxel_Missing('先補缺原量或已確認條件')
        if set(r) - set(_voxel_REQ[subtype_id]) - {'proposal'}:
            raise _voxel_Guard('未知欄位')
        if type(r['task']) is not str or r['task'] not in ('solve', 'check_proposal'):
            raise _voxel_Guard('task不符')
        a = _voxel_solve(subtype_id, r)
        if r['task'] == 'solve':
            if 'proposal' in r:
                raise _voxel_Guard('solve不混提案')
            return dict(decision='pass', answer=a)
        if r.get('proposal') is None:
            return dict(decision='confirm', answer=a, reason='先補待核想法，保留原題結果')
        return dict(decision='pass' if _voxel_equal(r['proposal'], a, subtype_id, r) else 'reject', answer=a)
    except _voxel_Missing as e:
        return dict(decision='confirm', answer=None, reason=str(e))
    except (_voxel_Guard, ValueError, TypeError, KeyError, OverflowError, ZeroDivisionError, RecursionError) as e:
        return dict(decision='block', answer=None, reason=str(e))

def evaluate(subtype, request):
 if type(subtype)is str and subtype in _voxel_SUBTYPES:
  return _voxel_evaluate(subtype,request)
 return _height_evaluate(subtype,request)

if __name__=='__main__':
 if len(sys.argv)>1 and sys.argv[1]in('evaluate','--evaluate'):
  try:
   raw=sys.stdin.read(65537)
   if len(raw)>65536:raise ValueError('request too large')
   def pairs(values):
    if len({k for k,v in values})!=len(values):raise ValueError('duplicate keys')
    return dict(values)
   def integer_parser(value):
    if len(value)>12:raise ValueError('integer literal too long')
    return int(value)
   def bad_number(value):raise ValueError('JSON floats and constants unsupported')
   request=json.loads(raw,object_pairs_hook=pairs,parse_int=integer_parser,parse_float=bad_number,parse_constant=bad_number)
   if type(request)is not dict or set(request)!={'subtypeId','input'}:raise ValueError('root fields invalid')
   result=evaluate(request['subtypeId'],request['input'])
  except(ValueError,TypeError,RecursionError,OverflowError,UnicodeError):
   result=dict(decision='block',answer=None,reason='請求格式、字面、大小或深度不適用')
  print(json.dumps(result,ensure_ascii=False))
 else:
  data=json.loads(pathlib.Path(__file__).with_name(PACK+'.json').read_text())
  for case in data['cases']:
   result=evaluate(case['subtypeId'],case['input'])
   assert(result['decision'],result['answer'])==(case['expectedDecision'],case['expectedAnswer']),case['id']
  print('PASS',len(data['cases']),'reviewed height and general voxel text contracts')
