"""Exact costs for seven ordered outputs on two slots, with replayable first separation."""
from itertools import product
from collections import Counter,deque
from deux27 import limited
from quatre24 import oracle
import json
def path(word,motif,budget):
    parents=[0,motif]+[{'A':1,'B':2,'X':3}[c] for c in word]
    start=(0,2,0);parent={start:None};queue=deque([start])
    while queue:
        s=queue.popleft();mask,i,spent=s
        if i==len(parents):
            steps=[]
            while parent[s]:
                old,line,keep=parent[s];steps.append([line,keep,*s]);s=old
            return list(reversed(steps))
        for line,deps in enumerate(parents):
            if 2<=line<i or mask>>line&1 or mask&deps!=deps:continue
            used=spent+int(line>i)
            if used>budget:continue
            for keep in [0]+[1<<j for j in range(len(parents)) if mask>>j&1]:
                live=keep|(1<<line);j=i
                while j<len(parents) and live>>j&1:live^=1<<j;j+=1
                new=(live,j,used)
                if new not in parent:parent[new]=(s,line,keep);queue.append(new)
def study():
    out=[]
    for motif in (0,1):
        hist=Counter();words=[];first=None
        for letters in product('ABX',repeat=7):
            if len(set(letters))<3:continue
            w=''.join(letters);deps=[(),(0,) if motif else ()]+[{'A':(0,),'B':(1,),'X':(0,1)}[c] for c in w]
            costs=[limited(w,motif,k) for k in (0,1,2)]+[oracle(deps,tuple(range(2,9)),True)]
            assert costs[0]==oracle(deps,tuple(range(2,9)),False) and costs==sorted(costs,reverse=True)
            hist[costs.index(costs[-1])]+=1;words.append([w,costs])
            if first is None and costs[1]>costs[-1]:
                trace=path(w,motif,2 if costs[2]==costs[-1] else 7);assert len(trace)==costs[-1]
                first=dict(word=w,costs=costs,trace=trace)
        out.append(dict(motif=motif,count=len(words),budget=hist,first=first,words=words))
    return out
if __name__=='__main__':print(json.dumps(study()))
