LEGOndary Grandmaster (Codeforces 1615F)
Tags: Math, combinatorics

After getting bored by playing with crayons, you decided to switch to Legos! Today, you're working with a long strip, with height $$$1$$$ and length $$$n$$$, some positions of which are occupied by $$$1$$$ by $$$1$$$ Lego pieces.In one second, you can either remove two adjacent Lego pieces from the strip (if both are present), or add two Lego pieces to adjacent positions (if both are absent). You can only add or remove Lego's at two adjacent positions at the same time, as otherwise your chubby fingers run into precision issues.You want to know exactly how much time you'll spend playing with Legos. You value efficiency, so given some starting state and some ending state, you'll always spend the least number of seconds to transform the starting state into the ending state. If it's impossible to transform the starting state into the ending state, you just skip it (so you spend $$$0$$$ seconds).The issue is that, for some positions, you don't remember whether there were Legos there or not (in either the starting state, the ending state, or both). Over all pairs of (starting state, ending state) that are consistent with your memory, find the total amount of time it will take to transform the starting state to the ending state. Print this value modulo $$$1\,000\,000\,007$$$ ($$$10^9 + 7$$$). 

Input: The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then $$$t$$$ cases follow.The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 2000$$$) — the size of the Lego strip.The second line of each test case contains a string $$$s$$$ of length $$$n$$$, consisting of the characters 0, 1, and ? — your memory of the starting state:   1 represents a position that definitely has a Lego piece,  0 represents a position that definitely does not have a Lego piece,  and ? represents a position that you don't remember. The third line of each test case contains a string $$$t$$$ of length $$$n$$$, consisting of the characters 0, 1, and ? — your memory of the ending state. It follows a similar format to the starting state.It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2000$$$.

Output: For each test case, output a single integer — the answer to the problem modulo $$$1\,000\,000\,007$$$ ($$$10^9 + 7$$$). 

Note: For the first test case, $$$00$$$ is the only possible starting state, and $$$11$$$ is the only possible ending state. It takes exactly one operation to change $$$00$$$ to $$$11$$$.For the second test case, some of the possible starting and ending state pairs are:   $$$(000, 011)$$$ — takes $$$1$$$ operation.  $$$(001, 100)$$$ — takes $$$2$$$ operations.  $$$(010, 000)$$$ — takes $$$0$$$ operations, as it's impossible to achieve the ending state. 

Sample Inputs:
6
2
00
11
3
???
???
3
??1
0?0
4
??0?
??11
5
?????
0??1?
10
?01??01?1?
??100?1???

Sample Outputs:
1
16
1
14
101
1674

Solution (Python):
import sys
I = lambda : [*map(int, sys.stdin.readline().split())]
M = 10 ** 9 + 7
facs = [1]
ifacs = [1]
for i in range(1, 5000):
    facs.append(facs[-1] * i % M)
    ifacs.append(ifacs[-1] * pow(i, M - 2, M) % M)

def binom(n, m):
    if m < 0 or m > n:
        return 0
    return facs[n] * ifacs[m] * ifacs[n - m] % M
(t,) = I()
for _ in range(t):
    (n,) = I()
    s = [*input()]
    t = [*input()]
    for i in range(n):
        if i % 2 == 0:
            if s[i] == '1':
                s[i] = '0'
            elif s[i] == '0':
                s[i] = '1'
            if t[i] == '1':
                t[i] = '0'
            elif t[i] == '0':
                t[i] = '1'
    s1 = s.count('1')
    sq = s.count('?')
    t1 = t.count('1')
    tq = t.count('?')
    qs = [0]
    qt = [0]
    os = [0]
    ot = [0]
    qs1 = []
    qt1 = []
    os1 = []
    ot1 = []
    for i in range(n - 1):
        if s[i] == '?':
            qs1.append(sq - qs[-1] - 1)
            qs.append(qs[-1] + 1)
        else:
            qs1.append(sq - qs[-1])
            qs.append(qs[-1])
        if s[i] == '1':
            os1.append(s1 - os[-1] - 1)
            os.append(os[-1] + 1)
        else:
            os1.append(s1 - os[-1])
            os.append(os[-1])
        if t[i] == '?':
            qt1.append(tq - qt[-1] - 1)
            qt.append(qt[-1] + 1)
        else:
            qt1.append(tq - qt[-1])
            qt.append(qt[-1])
        if t[i] == '1':
            ot1.append(t1 - ot[-1] - 1)
            ot.append(ot[-1] + 1)
        else:
            ot1.append(t1 - ot[-1])
            ot.append(ot[-1])
    qs1.append(0)
    qt1.append(0)
    os1.append(0)
    ot1.append(0)
    tot = 0
    for i in range(n):
        for j in range(n):
            if s[i] != '0' and t[j] != '0':
                tot += abs(i - j) * binom(qs[i] + qt[j], qt[j] + ot[j] - os[i]) * binom(qs1[i] + qt1[j], qt1[j] + ot1[j] - os1[i])
                tot %= M
    print(tot)

Solution (Python):
""""""
import io, os, sys
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
output = sys.stdout.write
DEBUG = os.environ.get('debug') is not None
if DEBUG:
    from inspect import currentframe, getframeinfo
    from re import search

def debug(*args):
    if not DEBUG:
        return
    frame = currentframe().f_back
    s = getframeinfo(frame).code_context[0]
    r = search('\\((.*)\\)', s).group(1)
    vnames = r.split(', ')
    var_and_vals = [f'{var}={val}' for (var, val) in zip(vnames, args)]
    prefix = f'{currentframe().f_back.f_lineno:02d}: '
    print(f"{prefix}{', '.join(var_and_vals)}")
INF = float('inf')
MOD = 10 ** 9 + 7
changes = {('0', '0'): [0], ('0', '1'): [-1], ('0', '?'): [0, -1], ('1', '0'): [1], ('1', '1'): [0], ('1', '?'): [0, 1], ('?', '0'): [0, 1], ('?', '1'): [-1, 0], ('?', '?'): [0, 0, 1, -1]}

def solve(N, S, T):
    for i in range(0, N, 2):
        if S[i] != '?':
            S[i] = '1' if S[i] == '0' else '0'
        if T[i] != '?':
            T[i] = '1' if T[i] == '0' else '0'
    L = [[0] * (2 * N + 1) for _ in range(N + 1)]
    L[0][0] = 1
    for i in range(N):
        ds = changes[S[i], T[i]]
        for j in range(-N, N + 1):
            for d in ds:
                if -N <= j + d <= N:
                    L[i + 1][j + d] = (L[i + 1][j + d] + L[i][j]) % MOD
    R = [[0] * (2 * N + 1) for _ in range(N + 1)]
    R[N][0] = 1
    for i in range(N - 1, -1, -1):
        ds = changes[S[i], T[i]]
        for j in range(-N, N + 1):
            for d in ds:
                if -N <= j + d <= N:
                    R[i][j + d] = (R[i][j + d] + R[i + 1][j]) % MOD
    res = 0
    for i in range(1, N + 1):
        for j in range(-N, N + 1):
            res = (res + abs(j * L[i][j] * R[i][-j])) % MOD
    return res

def main():
    T = int(input())
    for _ in range(T):
        N = int(input())
        S = list(input().decode().strip())
        T = list(input().decode().strip())
        out = solve(N, S, T)
        output(f'{out}\n')
if __name__ == '__main__':
    main()

Solution (Python):
""""""
import io, os, sys
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
output = sys.stdout.write
DEBUG = os.environ.get('debug') is not None
if DEBUG:
    from inspect import currentframe, getframeinfo
    from re import search

def debug(*args):
    if not DEBUG:
        return
    frame = currentframe().f_back
    s = getframeinfo(frame).code_context[0]
    r = search('\\((.*)\\)', s).group(1)
    vnames = r.split(', ')
    var_and_vals = [f'{var}={val}' for (var, val) in zip(vnames, args)]
    prefix = f'{currentframe().f_back.f_lineno:02d}: '
    print(f"{prefix}{', '.join(var_and_vals)}")
INF = float('inf')
MOD = 10 ** 9 + 7

def get_changes(s, t):
    if s == t == '0' or s == t == '1':
        return [0]
    if s == '0' and t == '1':
        return [-1]
    if s == '1' and t == '0':
        return [1]
    if s == '0' and t == '?' or (s == '?' and t == '1'):
        return [0, -1]
    if s == '1' and t == '?' or (s == '?' and t == '0'):
        return [0, 1]
    if s == '?' and t == '0' or (s == '1' and t == '?'):
        return [0, 1]
    if s == t == '?':
        return [0, 0, 1, -1]

def solve(N, S, T):
    for i in range(0, N, 2):
        if S[i] != '?':
            S[i] = '1' if S[i] == '0' else '0'
        if T[i] != '?':
            T[i] = '1' if T[i] == '0' else '0'
    L = [[0] * (2 * N + 1) for _ in range(N + 1)]
    L[0][0] = 1
    for i in range(N):
        ds = get_changes(S[i], T[i])
        for j in range(-N, N + 1):
            for d in ds:
                if -N <= j + d <= N:
                    L[i + 1][j + d] = (L[i + 1][j + d] + L[i][j]) % MOD
    R = [[0] * (2 * N + 1) for _ in range(N + 1)]
    R[N][0] = 1
    for i in range(N - 1, -1, -1):
        ds = get_changes(S[i], T[i])
        for j in range(-N, N + 1):
            for d in ds:
                if -N <= j + d <= N:
                    R[i][j + d] = (R[i][j + d] + R[i + 1][j]) % MOD
    res = 0
    for i in range(1, N + 1):
        for j in range(-N, N + 1):
            res = (res + abs(j * L[i][j] * R[i][-j])) % MOD
    return res

def main():
    T = int(input())
    for _ in range(T):
        N = int(input())
        S = list(input().decode().strip())
        T = list(input().decode().strip())
        out = solve(N, S, T)
        output(f'{out}\n')
if __name__ == '__main__':
    main()