Problem:
Score : 500 points

Problem Statement

Snuke has a string s.
From this string, Anuke, Bnuke, and Cnuke obtained strings a, b, and c, respectively, as follows:

Choose a non-empty (contiguous) substring of s (possibly s itself). Then, replace some characters (possibly all or none) in it with ?s.

For example, if s is mississippi, we can choose the substring ssissip and replace its 1-st and 3-rd characters with ? to obtain ?s?ssip.

You are given the strings a, b, and c.
Find the minimum possible length of s.

Constraints

1 \leq |a|, |b|, |c| \leq 2000

a, b, and c consists of lowercase English letters and ?s.

Input

Input is given from Standard Input in the following format:

a
b
c

Output

Print the minimum possible length of s.

Sample Input 1

a?c
der
cod

Sample Output 1

7

For example, s could be atcoder.

Sample Input 2

atcoder
atcoder
???????

Sample Output 2

7

a, b, and c may not be distinct.

Solution in Python (3.4.3) (judge verdict: Wrong Answer)

def inner(a,b,la,lb):
  for i in range(lb-la+1):
    for j in range(la):
      if a[j]=='?' or a[j]==b[i+j]:
        continue
      elif b[i+j]=='?':
        continue
      else:
        break
    else:
      return True
  return False

def head(a,b,la):
  for i in range(la,-1,-1):
    for j in range(i):
      if a[j]=='?' or a[j]==b[-(i-j)]:
        continue
      elif b[-(i-j)]=='?':
        continue
      else:
        break
    else:
      return b+a[i:]

def tail(a,b,la):
  for i in range(la,-1,-1):
    for j in range(i):
      if a[-(i-j)]=='?' or a[-(i-j)]==b[j]:
        continue
      elif b[j]=='?':
        continue
      else:
        break
    else:
      return a+b[i:]
      break

a=input()
la=len(a)
b=input()
lb=len(b)
c=input()
lc=len(c)
arr=[[a,la],[b,lb],[c,lc]]
arr=sorted(arr,key=lambda x:x[1])
a,la=arr[0]
b,lb=arr[1]
c,lc=arr[2]
tmp1=head(a,c,la)
tmp2=tail(a,c,la)
ans1=min(len(head(b,tmp1,lb)),len(tail(b,tmp1,lb)))
if inner(b,tmp1,lb,len(tmp1)):
  ans1=min(ans1,len(tmp1))
ans2=min(len(head(b,tmp2,lb)),len(tail(b,tmp2,lb)))
if inner(b,tmp2,lb,len(tmp2)):
  ans2=min(ans2,len(tmp2))
ans3=10**18
if inner(a,c,la,lc):
  ans3=min(len(head(b,c,lb)),len(tail(b,c,lb)))
  if inner(b,c,lb,lc):
    ans3=min(ans3,lc)
ansac=min(ans1,ans2,ans3)
tmp1=head(b,c,lb)
tmp2=tail(b,c,lb)
ans1=min(len(head(a,tmp1,la)),len(tail(a,tmp1,la)))
if inner(a,tmp1,la,len(tmp1)):
  ans1=min(ans1,len(tmp1))
ans2=min(len(head(a,tmp2,la)),len(tail(a,tmp2,la)))
if inner(a,tmp2,la,len(tmp2)):
  ans2=min(ans2,len(tmp2))
ans3=10**18
if inner(b,c,lb,lc):
  ans3=min(len(head(a,c,la)),len(tail(a,c,la)))
  if inner(a,c,la,lc):
    ans3=min(ans3,lc)
ansbc=min(ans1,ans2,ans3)
ans=min(ansac,ansbc)
print(ans)