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 Haskell (GHC 7.10.3) (judge verdict: Time Limit Exceeded)

import Control.Monad
import qualified Data.IntSet as IntSet

check :: String -> String -> Bool
check [] [] = True
check (a : as) (b : bs) = if a == b || a == '?' || b == '?' then check as bs else False
check _ _ = False

findMatches :: String -> String -> [Int]
findMatches s t = filter checkOffset [-lt-2000..ls+2000]
  where
  ls = length s
  lt = length t
  checkOffset offset =
    let b = max 0 offset
        e = min (lt + offset) ls
        l = e - b
        ss = if offset > 0 then drop offset s else s
        tt = if offset < 0 then drop (-offset) t else t
    in check (take l ss) (take l tt)

solve :: String -> String -> String -> Int
solve a b c = 
  let [la, lb, lc] = map length [a, b, c]
      calcLength x y = maximum [la, x + lb, y + lc] - minimum [0, x, y]
      xs = findMatches a b
      ys = findMatches a c
      zs = IntSet.fromList $ findMatches b c
      as = [calcLength x y | x <- xs, y <- ys, IntSet.member (y - x) zs]
  in if null as then la + lb + lc else minimum as

main :: IO ()
main = do
  [a, b, c] <- replicateM 3 getLine
  putStrLn $ show $ solve a b c