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.



Sample input:
a?c
der
cod


Sample output:
7

Submission status: Wrong Answer

Solution code:
def partial_match_table_mod(word):
    table = [0] * (len(word) + 1)
    table[0] = -1
    i, j = 0, 1

    while j < len(word):
        matched = (word[i] == word[j]) and (word[i] != "?")

        if not matched and i > 0:
            i = table[i]
        else:
            if matched:
                i += 1
            j += 1
            table[j] = i

    return table


def kmp_search_mod(string, pattern):
    table = partial_match_table_mod(pattern)
    i = j = 0
    while i < len(string) and j < len(pattern):
        if string[i] == pattern[j] or string[i] == "?" or pattern[j] == "?":
            i += 1
            j += 1
        elif j == 0:
            i += 1
        else:
            j = table[j]

    if j == len(pattern):
        return i - j
    else:
        return None


def solve_partial(s1, s2, s3):
    s1_add = s1 + "?" * len(s2)
    k1 = kmp_search_mod(s1_add, s2)
    assert k1 is not None
    s1_res = list(s1_add[:max(k1 + len(s2), len(s1))])
    for i in range(k1, min(len(s1), k1 + len(s2))):
        if s1[i] != s2[i - k1]:
            if s1[i] != "?":
                s1_res[i] = s1[i]
            else:
                s1_res[i] = s2[i - k1]
    for i in range(len(s1), k1 + len(s2)):
        s1_res[i] = s2[i - k1]
    s12 = "".join(s1_res)
    s12_add = s12 + "?" * len(s3)
    # print(s12_add)
    k2 = kmp_search_mod(s12_add, s3)
    assert k2 is not None
    # print(max(k2 + len(s3), len(s12)))
    return max(k2 + len(s3), len(s12))


def solve(s1, s2, s3):
    res = len(s1) + len(s2) + len(s3)
    res = min(res, solve_partial(s1, s2, s3))
    res = min(res, solve_partial(s1, s3, s2))
    res = min(res, solve_partial(s2, s1, s3))
    res = min(res, solve_partial(s2, s3, s1))
    res = min(res, solve_partial(s3, s1, s2))
    res = min(res, solve_partial(s3, s2, s1))
    return res


def main():
    s1 = input()
    s2 = input()
    s3 = input()
    res = solve(s1, s2, s3)
    print(res)
    # for r in res:
    #     print(r)


def test():
    assert solve("a?c", "der", "cod") == 7
    assert solve("atcoder", "atcoder", "???????") == 7


if __name__ == "__main__":
    test()
    main()

Submission status: Wrong Answer

Solution code:
def match(s1, s2, ind):
	j=0
	i=ind
	while(i<len(s1)):
		if s1[i]!='?' and s2[j]!='?' and s1[i]!=s2[j]:
			return False
		i+=1
		j+=1
	return True

def fusion(s1, s2):
	ind = len(s1)
	for i in range(len(s1)):
		if len(s1)-i <= len(s2):
			if match(s1, s2, i):
				ind = i
				break
	res = s1[:ind]+s2
	return res

a = input()
b = input()
c = input()

f1 = fusion( fusion(a,b), c)
f2 = fusion( fusion(a,c), b)
f3 = fusion( fusion(b,a), c)
f4 = fusion( fusion(b,c), a)
f5 = fusion( fusion(c,a), b)
f6 = fusion( fusion(c,b), a)
# ~ print("f1=",f1)
# ~ print("f2=",f2)
# ~ print("f3=",f3)
# ~ print("f4=",f4)
# ~ print("f5=",f5)
# ~ print("f6=",f6)

ans = min(len(f1),len(f2),len(f3),len(f4),len(f5),len(f6))

print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import permutations
import sys
def input():
	return sys.stdin.readline()[:-1]

def same(A, B):
	L = len(A)
	for l in range(L):
		if A[l] == B[l] or A[l] == "?" or B[l] == "?":
			pass
		else:
			return False
	return True

t = [input() for _ in range(3)]

a, b, c = t
la, lb, lc = len(a), len(b), len(c)

cross = [[0 for _ in range(3)] for _ in range(3)]

for i in range(1, min(len(a), len(b))+1):
	if same(a[la-i:], b[:i]):
		cross[0][1] = i
	if same(b[lb-i:], a[:i]):
		cross[1][0] = i

for i in range(1, min(len(b), len(c))+1):
	if same(b[lb-i:], c[:i]):
		cross[1][2] = i
	if same(c[lc-i:], b[:i]):
		cross[2][1] = i

for i in range(1, min(len(c), len(a))+1):
	if same(c[lc-i:], a[:i]):
		cross[2][0] = i
	if same(a[la-i:], c[:i]):
		cross[0][2] = i

if a in b:
	cross[0][1] = la
	cross[1][0] = la

if a in c:
	cross[0][2] = la
	cross[2][0] = la

if b in a:
	cross[0][1] = lb
	cross[1][0] = lb

if b in c:
	cross[2][1] = lb
	cross[1][2] = lb

if c in a:
	cross[0][2] = lc
	cross[2][0] = lc

if c in b:
	cross[2][1] = lc
	cross[1][2] = lc

ans = la+lb+lc
for p in permutations(range(3)):
	ans = min(ans, la+lb+lc - cross[p[0]][p[1]] - cross[p[1]][p[2]])
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1

def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(A, B, C):
    def f(a, b):
        for i in range(max(len(a)-len(b), 0), len(a)):
            for j in range(i, len(a)):
                if not (a[j] == '?' or b[j-i] == '?' or a[j] == b[j-i]):
                    break
            else:
                return i
        return None

    ans = len(A) + len(B) + len(C)
    for a, b, c in permutations([A, B, C]):
        ab = f(a, b)
        if ab is None:
            s = a + b
        else:
            s = a[:ab] + b
        bc = f(s, c)
        if bc is None:
            s += b
        else:
            s = s[:bc] + c
        ans = min(ans, len(s))


    return ans


def main():
    A = read_str()
    B = read_str()
    C = read_str()
    print(slv(A, B, C))

    # D = '?'*2000
    # print(slv(D, D, D))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import itertools

a=input()
b=input()
c=input()

def eq(s,t,i):

    for _s,_t in zip(s[-1*i:],t[:i]):

        if _s==_t:
            pass
        elif _s=='?' or _t=='?':
            pass
        else:
            return False
    return True

def join(s,t):
    retval=0
    for i in range(len(s)+1):
        if eq(s,t,i):
            retval=i

    prob1=s[:len(s)-retval]+t
    prob2=s+t[retval:]
    if prob1.count('?')<prob2.count('?'):
        return prob1
    else:
        return prob2

retval=10**10
for strs in itertools.permutations([a,b,c]):
    p=strs[0]
    q=strs[1]
    r=strs[2]
    pqr=join(join(p,q),r)
    pqr2=join(p,join(q,r))
    if(len(pqr)<retval):
        retval=len(pqr)
    if(len(pqr2)<retval):
        retval=len(pqr2)
print(retval)

Submission status: Wrong Answer

Solution code:
def check(a,b,c):
    ma = 0
    for i in range(min(len(a),len(b))):
        f = False
        for j in range(i+1):
            if a[-j-1] == b[i-j] or a[-j-1] == '?' or b[i-j] == '?':
                continue
            else:
                f = True
                break
        if f:
            break
        else:
            ma += 1
    mb = 0
    for i in range(min(len(b),len(c))):
        f = False
        for j in range(i+1):
            if b[-j-1] == c[i-j] or b[-j-1] == '?' or c[i-j] == '?':
                continue
            else:
                f = True
                break
        if f:
            break
        else:
            mb += 1
    # print(len(a)-ma , len(c) - mb , len(b))
    return len(a)-ma + len(c) - mb + len(b)

a = input()
b = input()
c = input()

s = float('inf')
s = min(s, check(a,b,c))
s = min(s, check(a,c,b))
s = min(s, check(b,c,a))
s = min(s, check(b,a,c))
s = min(s, check(c,b,a))
s = min(s, check(c,a,b))
print(s)

Submission status: Wrong Answer

Solution code:
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from itertools import permutations
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    def Z_algorithm(s):
        n = len(s)
        z = [0]*n
        z[0] = n
        c = 1
        for i in range(1,n):
            if i+z[i-c] < c+z[c]:
                z[i] = z[i-c]
            else:
                j = max(0,c+z[c]-i)
                while i+j < n and (s[j] == s[i+j] or s[i+j] == "?"):
                    j += 1
                z[i] = j
                c = i
        return z

    s = [input() for i in range(3)]
    ans = float("inf")
    for p in permutations(range(3)):
        a,b,c = s[p[0]],s[p[1]],s[p[2]]
        z = Z_algorithm(b+a)[len(b):]
        d = a+b
        zc = Z_algorithm(c+d)[len(c):]
        res = len(d)+len(c)
        for i in range(len(d)):
            if zc[i] >= len(d)-i or zc[i] >= len(c):
                k = max(len(d),i+len(c))
                if k < res:
                    res = k

        for j in range(len(a)):
            if z[j] >= len(a)-j or z[j] >= len(b):
                d = a[:j]
                for i in range(max(len(a)-j,len(b))):
                    k = i+j
                    if k < len(a):
                        if i < len(b) and a[k] == "?":
                            d += b[i]
                        else:
                            d += a[k]
                    else:
                        d += b[i]
            else:
                d = a+b
            zc = Z_algorithm(c+d)[len(c):]
            k = len(d)+len(c)
            for i in range(len(d)):
                if zc[i] >= len(d)-i or zc[i] >= len(c):
                    m = max(len(d),i+len(c))
                    if m < k:
                        k = m
            if k < res:
                res = k
        if res < ans:
            ans = res
    print(ans)
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
import sys

stdin = sys.stdin

ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))

ques = ord('?')

def Z_algo2(s):
    ls = len(s)
    lcp = [0]*ls
    lcp[0] = ls
    i,j = 1,0
    while i < ls:
        while i+j < ls and (s[j] == s[i+j] or s[j] == '?' or s[i+j] == '?'):
            j += 1
        lcp[i] = j
        if j == 0:
            i += 1
            continue
        k = 1
        while i+k < ls and k + lcp[k] < j:
            lcp[i+k] = lcp[k]
            k += 1
        i += k
        j -= k
    return lcp

def Z_algo(s,t):
  l = [0]*len(t)
  for i in range(len(t)):
    j = 0
    while j < len(s) and i+j < len(t) and (s[j] == t[i+j] or s[j] == ques or t[i+j] == ques):
      j += 1
    l[i] = j
  return l

a = list(map(ord, list(ns())))
b = list(map(ord, list(ns())))
c = list(map(ord, list(ns())))

l = [a, b, c]
g = [[0]*3 for _ in range(3)]
for i in range(3):
    for j in range(3):
        if i != j:
            g[i][j] = Z_algo(l[i],l[j])
            # print(i,j,g[i][j])
ans = sum(len(x) for x in l)
for i in range(3):
    for j in range(3):
        if i == j: continue
        k = 3-i-j
        li = [ii for ii in range(len(l[i])) if g[j][i][ii] >= min(len(l[i]) - ii, len(l[j]))]
        lj = [ii for ii in range(len(l[j])) if g[k][j][ii] >= min(len(l[j]) - ii, len(l[k]))]
        for ii in li:
            for jj in lj:
                kk = ii + jj
                if kk >= len(l[i]) or g[k][i][kk] >= min(len(l[i]) - kk, len(l[k])):
                    c = max(len(l[i]), ii + len(l[j]), kk + len(l[k]))
                    if ans > c:
                        # print(i,j,k,ii,jj,c)
                        ans = c
print(ans)

Submission status: Wrong Answer

Solution code:
class KMP:
    def __init__(self, P):
        self.P = P
        self.N = len(P)
        self.T = [0] * (self.N + 1)
        self._compile()

    def _compile(self):
        j = 0
        self.T[0] = -1
        for i in range(1, self.N):
            self.T[i] = j
            j += 1 if self.P[i] == self.P[j] or self.P[i]=='?' or self.P[j]=='?' else -j
        self.T[self.N] = j

    def search(self, S):
        NS = len(S)
        i = m = 0
        A = []
        while m + i < NS:
            if self.P[i] == S[m + i] or S[m+i]=='?':#
                i += 1
                if i != self.N:
                    continue
                A.append(m)
            m += i - self.T[i]
            i = max(0, self.T[i])
        return A

a=list(input())
b=list(input())
c=list(input())
s=[a,b,c]
zn=len(a)+len(b)+len(c)
def solve(a,b,c):
    z=a+['?']*zn
    r=len(a)
    kl=KMP(b).search(z)
    k=min(kl)
    for i in range(len(b)):
        if b[i]!='?':
            z[k+i]=b[i]
    r=max(r,k+len(b))
    kl=KMP(c).search(z)
    k=min(kl)
    #print(kl)
    #print(z)
    return max(r,k+len(c))
ans=10**10
for i in range(3):
    for j in range(3):
        for k in range(3):
            if i==j or j==k or k==i:
                continue
            ans=min(ans,solve(s[i],s[j],s[k]))
print(ans)

Submission status: Wrong Answer

Solution code:
import collections
a = input()
b = input()
c = input()
ans = 0
abc = a+b+c
abc2 = collections.Counter(abc)
ans += len(abc2)
if a == b or a == c or b == c:
  print(len(a))
else:
  if "?" in abc:
      ans += abc.count("?")-1
  print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np

a = input()
b = input()
c = input()


dic = {"a" : 1, "b" : 2, "c" : 3, "d" : 4, "e" : 5, "f" : 6, 
 "g" : 7,
 "h" : 8,
 "i" : 9,
 "j" : 10,
 "k" : 11,
 "l" : 12,
 "m" : 13,
 "n" : 14,
 "o" : 15,
 "p" : 16,
 "q" : 17,
 "r" : 18,
 "s" : 19,
 "t" : 20,
 "u" : 21,
 "v" : 22,
 "w" : 23,
 "x" : 24,
 "y" : 25,
 "z" : 26,
 "?" : np.nan,
}

aa = []
for s in a:
    aa.append(dic[s])
aa = np.array(aa)

bb = []
for s in b:
    bb.append(dic[s])
bb = np.array(bb)

cc = []
for s in c:
    cc.append(dic[s])
cc = np.array(cc)

def comp(aa, bb):
    ma = min([len(aa), len(bb)])
    same = 0
    for k in range(ma):
        a = np.nanmax(np.abs(aa[-k-1:] - bb[:k+1]))
        if np.isnan(a):
            a = 0
        if a == 0:
            same = k + 1
    return same

same_ab = comp(aa, bb)
same_ac = comp(aa, cc)
same_ba = comp(bb, aa)
same_bc = comp(bb, cc)
same_ca = comp(cc, aa)
same_cb = comp(cc, bb)

base = len(a) + len(b) + len(c)

ans = base - max([same_ab + same_bc,
same_ac + same_cb,
same_ba + same_ac,
same_bc + same_ca,
same_ca + same_ab,
same_cb + same_ba])

print(ans)

Submission status: Wrong Answer

Solution code:
def judge(x, y):
    if len(x)!=len(y):
        return 0
    for i in range(len(x)):
        if x[i]!=y[i] and x[i]!='?' and y[i]!='?':
            return 0
    return 1

a=input()
b=input()
c=input()
ngs=max(len(a), len(b), len(c))

max1=0
max2=0
max3=0
max4=0
max5=0
max6=0

for i in range(ngs):
    ok=1
    if len(a)<i+1:
        ok=0
        break
    else:
        if len(b)<i+1:
            ok=0
            pass
        else:
            if judge(b[len(b)-(i+1):], a[:i+1])==1:
                max1=i+1
            else:
                ok=0
        if len(c)<i+1:
            ok=0
            pass
        else:
            if judge(c[len(c)-(i+1):], a[:i+1])==1:
                max2=i+1
            else:
                ok=0

for i in range(ngs):
    ok=1
    if len(b)<i+1:
        ok=0
        break
    else:
        if len(c)<i+1:
            ok=0
            pass
        else:
            if judge(c[len(c)-(i+1):], b[:i+1])==1:
                max3=i+1
            else:
                ok=0
        if len(a)<i+1:
            ok=0
            pass
        else:
            if judge(a[len(a)-(i+1):], b[:i+1])==1:
                max4=i+1
            else:
                ok=0

for i in range(ngs):
    ok=1
    if len(c)<i+1:
        ok=0
        break
    else:
        if len(a)<i+1:
            ok=0
            pass
        else:
            if judge(a[len(a)-(i+1):], c[:i+1])==1:
                max5=i+1
            else:
                ok=0
        if len(b)<i+1:
            ok=0
            pass
        else:
            if judge(b[len(b)-(i+1):], c[:i+1])==1:
                max6=i+1
            else:
                ok=0

naiho1=0
naiho2=0
naiho3=0
naiho4=0
naiho5=0
naiho6=0

if len(a)>len(b)+1:
    kaisu=len(a)-len(b)-1
    for i in range(kaisu):
        if judge(a[i+1:i+1+len(b)], b)==1:
            naiho1=1
if len(a)>len(c)+1:
    kaisu=len(a)-len(c)-1
    for i in range(kaisu):
        if judge(a[i+1:i+1+len(c)], c)==1:
            naiho2=1
if len(b)>len(c)+1:
    kaisu=len(b)-len(c)-1
    for i in range(kaisu):
        if judge(b[i+1:i+1+len(c)], c)==1:
            naiho3=1
if len(b)>len(a)+1:
    kaisu=len(b)-len(a)-1
    for i in range(kaisu):
        if judge(b[i+1:i+1+len(a)], a)==1:
            naiho4=1
if len(c)>len(a)+1:
    kaisu=len(c)-len(a)-1
    for i in range(kaisu):
        if judge(c[i+1:i+1+len(a)], a)==1:
            naiho5=1
if len(c)>len(b)+1:
    kaisu=len(c)-len(b)-1
    for i in range(kaisu):
        if judge(c[i+1:i+1+len(b)], b)==1:
            naiho6=1

#print(max1, max2, max3, max4, max5, max6)
if naiho1==1 and naiho2==1:
    print(len(a))
elif naiho3==1 and naiho4==1:
    print(len(b))
elif naiho5==1 and naiho6==1:
    print(len(c))
elif naiho1==1 or naiho6==1:
    hiku=max(max2, max5)
    print(len(a)+len(c)-hiku)
elif naiho2==1 or naiho3==1:
    hiku=max(max1, max4)
    print(len(a)+len(b)-hiku)
elif naiho4==1 or naiho5==1:
    hiku=max(max3, max6)
    print(len(b)+len(c)-hiku)
else:
    hiku=max(max1+max3, max3+max5, max5+max1, max2+max4, max4+max6, max6+max2)
    print(len(a)+len(b)+len(c)-hiku)

Submission status: Wrong Answer

Solution code:
a=list(input())
b=list(input())
c=list(input())

def union(a,b):
  db=0
  for i in range(len(a)):
    to=0
    for j in range(len(b)):
      if i+j==len(a):
        to=len(b)-j
        break
      elif a[i+j]==b[j] or a[i+j]=="?" or b[j]=="?":
        pass
      else:
        to=-1
        break
    if to==0:
      db=a
      break
    elif to>0:
      db=a
      for bi in range(len(b)-to):
        if db[-(len(b)-to)+bi]=="?":
          db[-(len(b)-to)+bi]=b[bi]
      db=a+b[-to:]
      break
  if db==0:
    db=a+b
  return db

ans=float("inf")
for x,y,z in [[a,b,c],[b,a,c],[b,c,a],[c,b,a],[c,a,b],[a,c,b]]:
  ans=min(ans,len(union(union(x,y),z)))
  ans=min(ans,len(union(z,union(x,y))))
    
print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import permutations
import sys
def input():
	return sys.stdin.readline()[:-1]

def same(A, B):
	L = len(A)
	for l in range(L):
		if A[l] == B[l] or A[l] == "?" or B[l] == "?":
			pass
		else:
			return False
	return True

t = [input() for _ in range(3)]

a, b, c = t
la, lb, lc = len(a), len(b), len(c)

cross = [[0 for _ in range(3)] for _ in range(3)]

for i in range(1, min(len(a), len(b))+1):
	if same(a[la-i:], b[:i]):
		cross[0][1] = i
	if same(b[lb-i:], a[:i]):
		cross[1][0] = i

for i in range(1, min(len(b), len(c))+1):
	if same(b[lb-i:], c[:i]):
		cross[1][2] = i
	if same(c[lc-i:], b[:i]):
		cross[2][1] = i

for i in range(1, min(len(c), len(a))+1):
	if same(c[lc-i:], a[:i]):
		cross[2][0] = i
	if same(a[la-i:], c[:i]):
		cross[0][2] = i

ans = la+lb+lc
for p in permutations(range(3)):
	ans = min(ans, la+lb+lc - cross[p[0]][p[1]] - cross[p[1]][p[2]])
print(ans)

Submission status: Wrong Answer

Solution code:
import itertools

a=input()
b=input()
c=input()

def eq(s,t,i):

    for _s,_t in zip(s[-1*i:],t[:i]):

        if _s==_t:
            pass
        elif _s=='?' or _t=='?':
            pass
        else:
            return False
    return True

def join(s,t):
    retval=0
    for i in range(len(s)+1):
        if eq(s,t,i):
            retval=i

    prob1=s[:len(s)-retval]+t
    prob2=s+t[retval:]
    if prob1.count('?')<prob2.count('?'):
        return prob1
    else:
        return prob2

retval=10**10
for strs in itertools.permutations([a,b,c]):
    p=strs[0]
    q=strs[1]
    r=strs[2]
    pqr=join(join(p,q),r)
    if(len(pqr)<retval):
        retval=len(pqr)
print(retval)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
a = input()
b = input()
c = input()

def equal(s,t):
  if len(s)!=len(t):
    return False
  for i in range(len(s)):
    if s[i]!='?' and t[i]!='?' and s[i]!=t[i]:
      return False
  return True

def compare(s,t):
  # sの先頭n文字 と tの末尾n文字が一致している ようなnの最大値
  length = min(len(s), len(t))
  n = 0
  for i in range(1,length+1):
    if equal(s[:i], t[-i:]):
      n = i
  return n

def subset(s,t):
  # sの部分文字列の中にtがあるかどうか
  if len(t)>len(s):
    return False
  for i in range(len(s)-len(t)+1):
    if equal(s[i:i+len(t)], t):
      return True
  return False

def calculator():
  if substring[0] and substring[1]:
    return length[0]
  if substring[2] and substring[3]:
    return length[1]
  if substring[4] and substring[5]:
    return length[2]
  
  result = sum(length)
  
  # a->b
  tmp_str = a + b[common[0]:]
  if subset(tmp_str, c):
    result = min(result, len(tmp_str))
  else:
    result = min(result, len(tmp_str)+length[2]-max(common[4],common[3]))
  
  # a->c
  tmp_str = a + c[common[1]:]
  if subset(tmp_str, b):
    result = min(result, len(tmp_str))
  else:
    result = min(result, len(tmp_str)+length[1]-max(common[2],common[5]))
  
  # b->a
  tmp_str = b + a[common[2]:]
  if subset(tmp_str, c):
    result = min(result, len(tmp_str))
  else:
    result = min(result, len(tmp_str)+length[2]-max(common[5],common[1]))
  
  # b->c
  tmp_str = b + c[common[3]:]
  if subset(tmp_str, a):
    result = min(result, len(tmp_str))
  else:
    result = min(result, len(tmp_str)+length[0]-max(common[0],common[4]))
  
  # c->a
  tmp_str = c + a[common[4]:]
  if subset(tmp_str, b):
    result = min(result, len(tmp_str))
  else:
    result = min(result, len(tmp_str)+length[1]-max(common[3],common[0]))
  
  # c->b
  tmp_str = c + b[common[5]:]
  if subset(tmp_str, a):
    result = min(result, len(tmp_str))
  else:
    result = min(result, len(tmp_str)+length[0]-max(common[1],common[2]))
  
  return result

length = [len(a), len(b), len(c)]
common = [compare(a,b), compare(a,c), compare(b,a),
          compare(b,c), compare(c,a), compare(c,b)]
substring = [subset(a,b), subset(a,c), subset(b,a),
             subset(b,c), subset(c,a), subset(c,b)]

print(calculator())

Submission status: Wrong Answer

Solution code:
class KMP:
    def __init__(self, P):
        self.P = P
        self.N = len(P)
        self.T = [0] * (self.N + 1)
        self._compile()

    def _compile(self):
        j = 0
        self.T[0] = -1
        for i in range(1, self.N):
            self.T[i] = j
            j += 1 if self.P[i] == self.P[j] or self.P[i]=='?' or self.P[j]=='?' else -j
        self.T[self.N] = j

    def search(self, S):
        NS = len(S)
        i = m = 0
        A = []
        while m + i < NS:
            if self.P[i] == S[m + i] or self.P[i]=='?' or S[m+i]=='?':#
                i += 1
                if i != self.N:
                    continue
                A.append(m)
            m += i - self.T[i]
            i = max(0, self.T[i])
        return A

a=list(input())
b=list(input())
c=list(input())
s=[a,b,c]
zn=len(a)+len(b)+len(c)
def solve(a,b,c):
    z=a+['?']*zn
    r=len(a)
    kl=KMP(b).search(z)
    k=min(kl)
    for i in range(len(b)):
        if b[i]!='?':
            z[k+i]=b[i]
    r=max(r,k+len(b))
    kl=KMP(c).search(z)
    k=min(kl)
    #print(kl)
    #print(z)
    return max(r,k+len(c))
ans=10**10
for i in range(3):
    for j in range(3):
        for k in range(3):
            if i==j or j==k or k==i:
                continue
            ans=min(ans,solve(s[i],s[j],s[k]))
print(ans)

Submission status: Wrong Answer

Solution code:
a=input()
b=input()
c=input()
X=[a,b,c]

def mix(s,t):
    for length in range(min(len(t),len(s)),0,-1):
        u=s[-length:]
        v=t[:length]

        #print(u,v)

        for i in range(length):
            if u[i]==v[i] or u[i]=="?" or v[i]=="?":
                continue
            else:
                break
        else:
            ret=""
            for i in range(length):
                if u[i]=="?":
                    ret+=v[i]
                else:
                    ret+=u[i]
                
            yield s[:-length]+ret+t[length:]

    yield s+t

from itertools import permutations
ITE=permutations([0,1,2])
ANS=[]
for i,j,k in ITE:
    for l in mix(X[i],X[j]):
        ANS.extend(list(mix(l,X[k])))
        ANS.extend(list(mix(X[k],l)))

L=1<<30
for a in ANS:
    L=min(L,len(a))
print(L)

Submission status: Wrong Answer

Solution code:
import itertools
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353


A, B, C = [sys.stdin.buffer.readline().decode().rstrip() for _ in range(3)]
A = list(map(ord, A))
B = list(map(ord, B))
C = list(map(ord, C))

memo = {}
Q = ord('?')


def get_ok_idx(A, B):
    key = str(A) + str(B)
    if key in memo:
        return memo[key]
    ret = []
    for i in range(len(A) + 1):
        for a, b in zip(A[i:], B):
            if a != b and a != Q and b != Q:
                break
        else:
            ret.append(i)
    memo[key] = ret
    return ret


# A = np.array(A, dtype=int)
# B = np.array(B, dtype=int)
# C = np.array(C, dtype=int)

def solve(A, B, C):
    ok_ab = get_ok_idx(A, B)
    ok_bc = get_ok_idx(B, C)
    ok_ac = [False] * (len(A) + 1)
    for i in get_ok_idx(A, C):
        ok_ac[i] = True
    ret = INF
    for ab, bc in itertools.product(ok_ab, ok_bc):
        if ab + bc >= len(A) or ok_ac[ab + bc]:
            ret = min(ret, max(len(A), ab + len(B), ab + bc + len(C)))
    return ret


ans = len(A) + len(B) + len(C)
ans = min(ans, solve(A, B, C))
ans = min(ans, solve(A, C, B))
ans = min(ans, solve(B, A, C))
ans = min(ans, solve(B, C, A))
ans = min(ans, solve(C, A, B))
ans = min(ans, solve(C, B, A))
print(ans)

Submission status: Wrong Answer

Solution code:
class KMP:
    def __init__(self, P):
        self.P = P
        self.N = len(P)
        self.T = [0] * (self.N + 1)
        self._compile()

    def _compile(self):
        j = 0
        self.T[0] = -1
        for i in range(1, self.N):
            self.T[i] = j
            j += 1 if self.P[i] == self.P[j] or self.P[j]=='?' else -j
        self.T[self.N] = j

    def search(self, S):
        NS = len(S)
        i = m = 0
        A = []
        while m + i < NS:
            if self.P[i] == S[m + i] or self.P[i]=='?' or S[m+i]=='?':#
                i += 1
                if i != self.N:
                    continue
                A.append(m)
            m += i - self.T[i]
            i = max(0, self.T[i])
        return A

a=list(input())
b=list(input())
c=list(input())
s=[a,b,c]
zn=len(a)+len(b)+len(c)
def solve(a,b,c):
    z=a+['?']*zn
    r=len(a)
    kl=KMP(b).search(z)
    k=min(kl)
    for i in range(len(b)):
        if b[i]!='?':
            z[k+i]=b[i]
    r=max(r,k+len(b))
    kl=KMP(c).search(z)
    k=min(kl)
    #print(kl)
    #print(z)
    return max(r,k+len(c))
ans=10**10
for i in range(3):
    for j in range(3):
        for k in range(3):
            if i==j or j==k or k==i:
                continue
            ans=min(ans,solve(s[i],s[j],s[k]))
print(ans)

Submission status: Wrong Answer

Solution code:
a = input()
b = input()
c = input()

s = [a, b, c]
le = [len(a), len(b), len(c)]

def check(s1, s2, n) :
    flg = True
    for i in range(n) :
        if s1[-n+i] != s2[i] :
            if s1[-n+i] != "?" and s2[i] != "?" :
                flg = False
    return flg

ans = [0 for _ in range(6)]

for i in range(min(le[0],le[1])) :
    if check(s[0], s[1], i+1) :
        ans[0] = i+1
for i in range(min(le[1],le[2])) :
    if check(s[1], s[2], i+1) :
        ans[1] = i+1
for i in range(min(le[2],le[0])) :
    if check(s[2], s[0], i+1) :
        ans[2] = i+1
for i in range(min(le[0],le[2])) :
    if check(s[0], s[2], i+1) :
        ans[3] = i+1
for i in range(min(le[2],le[1])) :
    if check(s[2], s[1], i+1) :
        ans[4] = i+1
for i in range(min(le[1],le[0])) :
    if check(s[1], s[0], i+1) :
        ans[5] = i+1

ans2 = [ans[0]+ans[1], ans[3]+ans[4], ans[5]+ans[3], ans[1]+ans[2], ans[2]+ans[0], ans[4]+ans[5]]

print(sum(le) - max(ans2))

Submission status: Wrong Answer

Solution code:
def solorder(a, b, c):

    def minpos(x, y):
        i = 0
        j = 0
        res = 0
        while i<len(x) and j<len(y):
            a = x[i]
            b = y[j]
            if a=='?' or b=='?' or a==b:
                i += 1
                j += 1
                continue
            # reset
            j = 0
            b = y[j]
            i1 = x.find(b, res+1)
            if i1 == -1:
                i1 = len(x)
            i2 = x.find('?', res+1)
            if i2 == -1:
                i2 = len(x)
            i = min(i1, i2)
            res = i
        return res

    i = minpos(a, b)
    com = len(a) - i
    ext = max(len(b) - com, 0)
    ab = a + b[-ext:] if ext else a

    i = minpos(ab, c)
    com = len(ab) - i
    ext = max(len(c) - com, 0)
    return len(ab) + ext

def sol(a,b,c):
    return min(solorder(x, y, z) for x, y, z in (
        (a, b, c),
        (a, c, b),
        (b, a, c),
        (b, c, a),
        (c, a, b),
        (c, b, a),
    ))

def main():
    a = input().strip()
    b = input().strip()
    c = input().strip()
    print(sol(a, b, c))

if __name__ == '__main__':
    main()