"""Three turns, dwell two. Compare transfer with explicitly enumerated switch schedules."""
from collections import Counter,defaultdict
from functools import lru_cache
from itertools import combinations,product
import json

N=18

@lru_cache(None)
def runs(start,a,b,c,k):
    ordered=sorted((6*n+(start+j)%6,j) for j,group in enumerate((a,b,c)) for n in group)
    end=changes=0
    for (t,i),(s,j) in zip(ordered,ordered[1:]):
        if i!=j:
            changes+=1;end=max(end+2,t+1)
            if changes>k or end>s:return False
    return end<=N-2

def transfer(sizes,k):
    choices=[list(combinations(range(3),n)) for n in sizes];total=0
    for a,b in product(*choices[:2]):
        states={(a,b):1}
        for i,pool in enumerate(choices[2:]+[[a],[b]]):
            current=defaultdict(int)
            for (x,y),count in states.items():
                for z in pool:
                    if runs(i,x,y,z,k):current[y,z]+=count
            states=current
        total+=sum(states.values())
    return total

def reachable(d,k):
    masks=set()
    for n in range(k+1):
        for cuts in combinations(range(2,N-1),n):
            bounds=(0,*cuts,N)
            if any(b-a<2 for a,b in zip(bounds,bounds[1:])):continue
            for shifts in product((-1,0,1),repeat=n+1):
                hit=[t for a,b,j in zip(bounds,bounds[1:],shifts) for t in range(a,b) if (t-d-j)%6==5]
                masks.update(sum(1<<t for t in group) for group in combinations(hit,4))
    return masks

def study():
    reach=[sum(1<<t for t in range(N) if (t-d-5)%6 in (0,1,5)) for d in range(6)]
    tables=[[reachable(d,k) for d in range(6)] for k in (2,3)]
    direct=Counter();first=None
    for times in combinations(range(N),8):
        mask=sum(1<<t for t in times);targets=[mask&h for h in reach]
        if any(h.bit_count()!=4 for h in targets):continue
        sizes=tuple(sum(t%6==j for t in times) for j in range(6))
        flags=[all(x in pool for x,pool in zip(targets,tab)) for tab in tables]
        for k,flag in enumerate(flags):direct[sizes,k]+=int(flag)
        if flags==[False,True] and first is None:first=times
    rows=[]
    for a,b,c in product(range(4),repeat=3):
        if a+b+c!=4:continue
        sizes=(a,b,c)*2;two,three=[transfer(sizes,k) for k in (2,3)]
        assert [two,three]==[direct[sizes,i] for i in (0,1)]
        rows.append(dict(sizes=sizes,two=two,three=three,gain=three-two))
    return dict(first=first,minimum=8 if first else None,rows=rows,total=sum(r['gain'] for r in rows))
if __name__=='__main__':print(json.dumps(study()))
