"""A finite combination of shifted Motzkin numbers for the prefix 1,...,k.
Implements Q5.2 of Clifton, Harris and Khaqan, arXiv:2611.29890.
"""
from collections import Counter
from functools import lru_cache
from itertools import product
from math import comb


def park(word, size):
    board=[0]*size
    for car,p in enumerate(word,1):
        prev=board[p]
        if prev:
            board[board.index(0)]=prev
        board[p]=car
    return board


@lru_cache(None)
def prefix_constants(k):
    row=[]
    for j in range(k+1):
        ways=0
        for word in product(range(k+j),repeat=k):
            board=park(word,k+j)
            if not all(board[k:]): continue
            for p in range(k,k+j):
                board[board.index(0)]=board[p]
                board[p]=-1
            ways += board[:k] == list(range(1,k+1))
        row.append(ways)
    return tuple(row)


def add(poly, deg, val):
    poly[deg]+=val
    if poly[deg]==0: del poly[deg]


@lru_cache(None)
def linear_coefficients(k):
    # t=1/z; M^2=(t^2-t)M-t^2. Represent each reduced power as A(t)M+B(t).
    polynomial=Counter()
    for j,b in enumerate(prefix_constants(k)):
        for i in range(j+1): add(polynomial,i+1,b*comb(j,i)*(-1)**(j-i))
    a,b=Counter(), Counter({0:1}); answer=Counter()
    for i in range(1,k+2):
        aa,bb=b.copy(),Counter()
        for deg,v in a.items():
            add(aa,deg+2,v); add(aa,deg+1,-v); add(bb,deg+2,-v)
        a,b=aa,bb
        for deg,v in a.items():add(answer,deg,polynomial[i]*v)
    return tuple(sorted(answer.items()))


@lru_cache(None)
def motzkin(n):
    if n==0: return 1
    return motzkin(n-1)+sum(motzkin(i)*motzkin(n-2-i) for i in range(n-1))


def value(n,k):
    assert n>k>=0
    return sum(c*motzkin(n-k+d) for d,c in linear_coefficients(k))


if __name__=='__main__':
    for n in range(1,7):
        outcomes=Counter(tuple(park(word,n)) for word in product(range(n),repeat=n))
        for k in range(n):
            target=tuple(range(1,k+1))+tuple(range(n,k,-1))
            assert value(n,k)==outcomes[target]
    for k in range(1,5):
        print('k =',k,'prefix weights',prefix_constants(k),'coefficients (shift from n-k, weight)',linear_coefficients(k))
    print('n=7, k=3:',value(7,3))
