"""Compare budgets of zero, one, two and unlimited early constructions on six outputs."""
from collections import deque,Counter
from itertools import product
import json
from quatre24 import oracle

def limited(word,motif,cap):
    parents=[0,motif]+[{'A':1,'B':2,'X':3}[c] for c in word]
    order=tuple(range(2,len(parents)));start=(0,0,0)
    q=deque([(start,0)]);seen={start}
    while q:
        (mask,i,spent),dist=q.popleft()
        if i==len(order):return dist
        for line,ps in enumerate(parents):
            if mask>>line&1 or mask&ps!=ps or line in order[:i]:continue
            early=line in order[i+1:]
            if spent+early>cap:continue
            for keep in [0]+[1<<v for v in range(len(parents)) if mask>>v&1]:
                live=keep|(1<<line);j=i
                while j<len(order) and live>>order[j]&1:live^=1<<order[j];j+=1
                state=(live,j,spent+early)
                if state not in seen:seen.add(state);q.append((state,dist+1))
    raise ValueError('unreachable')

def study():
    result=[]
    for motif in (0,1):
        hist=Counter();first={};words=[]
        for w in product('ABX',repeat=6):
            if len(set(w))!=3:continue
            word=''.join(w);ps=[(),(0,) if motif else ()]+[{'A':(0,),'B':(1,),'X':(0,1)}[c] for c in word]
            costs=[limited(word,motif,k) for k in range(3)]
            costs.append(oracle(ps,tuple(range(2,8)),True))
            assert costs[0]==oracle(ps,tuple(range(2,8)),False) and costs==sorted(costs,reverse=True)
            k=costs.index(costs[-1]);hist[k]+=1;first.setdefault(k,[word,costs]);words.append([word,costs])
        result.append(dict(motif=motif,count=len(words),budget=hist,first=first,words=words))
    return result
if __name__=='__main__':print(json.dumps(study()))
