Problem:


Score : 600 points

Problem Statement

Let us define the oddness of a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n} as \sum_{i = 1}^n |i - p_i|.

Find the number of permutations of {1,\ 2,\ ...,\ n} of oddness k, modulo 10^9+7.

Constraints

All values in input are integers.

1 \leq n \leq 50

0 \leq k \leq n^2

Input

Input is given from Standard Input in the following format:

n k

Output

Print the number of permutations of {1,\ 2,\ ...,\ n} of oddness k, modulo 10^9+7.

Sample Input 1

3 2

Sample Output 1

2

There are six permutations of {1,\ 2,\ 3}. Among them, two have oddness of 2:  {2,\ 1,\ 3} and {1,\ 3,\ 2}.

Sample Input 2

39 14

Sample Output 2

74764168



Sample input:
3 2


Sample output:
2

Submission status: Runtime Error

Solution code:
def main():

    """ convenient functions
    # for i, a in enumerate(iterable)
    # q, mod = divmod(a, b)
    # divmod(x, y) returns the tuple (x//y, x%y)
    # Higher-order function: reduce(operator.mul, xyz_count, 1)
    # manage median(s) using two heapq https://atcoder.jp/contests/abc127/tasks/abc127_f
    """

    """convenient decorator
    # @functools.lru_cache():
    # to facilitate use of recursive function
        # ex:
        # from functools import lru_cache
        # import sys
        # sys.setrecursionlimit(10**9)
        # @lru_cache(maxsize=None)
        # def fib(n):
        #     if n < 2:
        #         return n
        #     return fib(n-1) + fib(n-2)
        # print(fib(1000))
    """
    
    # import numpy as np
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product # https://docs.python.org/ja/3/library/itertools.html
    # accumulate() returns iterator! to get list: list(accumulate())
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  # prime factor
        b, e = 2, 0  # base, exponent
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        # TODO: How should I do when n - r is negative?
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict # https://docs.python.org/ja/3/library/collections.html#collections.deque
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest # https://docs.python.org/ja/3/library/heapq.html
    from copy import deepcopy, copy # https://docs.python.org/ja/3/library/copy.html
    import operator
    from operator import itemgetter
    # ex1: List.sort(key=itemgetter(1))
    # ex2: sorted(tuples, key=itemgetter(1,2))
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd # Deprecated since version 3.5: Use math.gcd() instead.
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)

    # first create factorial_list
    # fac_list = mod_factorial_list(n)
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) # Recursive function in python is slow!
    def modinv(a, p = MOD):
        # evaluate reciprocal using Fermat's little theorem:
        # a**(p-1) is identical to 1 (mod p) when a and p is coprime
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        # fac_list = modfactorial_list(100)
        # print(modcomb(100, 5, modfactorial_list(100)))
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    """ initialize variables and set inputs
    # initialize variables
        # to initialize list, use [0] * n
        # to initialize two dimentional array, use [[0] * N for _ in range(N)]
    # set inputs
        # open(0).read() is a convenient method:
        # ex) n, m, *x = map(int, open(0).read().split())
        #     min(x[::2]) - max(x[1::2])
        # ex2) *x, = map(int, open(0).read().split())
        #     don't forget to add comma after *x if only one variable is used
    # preprocessing
        # transpose = [x for x in zip(*data)]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
        # flat = [flatten for inner in data for flatten in inner]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [1, 2, 3, 4, 5, 6, 7, 8, 9]
    # calculate and output
        # output pattern
        # ex1) print(*l) => when l = [2, 5, 6], printed 2 5 6
    """

    # functions used
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    R = lambda: list(map(int, r().split()))
    Rmap = lambda: map(int, r().split())
    Rfloat = lambda: list(map(float, r().split()))
    Rtuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    # single int: int(r())
    # single string: r()
    # single float: float(r())
    # line int: R()
    # line string: r().split()
    # line (str, int, int): [j if i == 0 else int(j) for i, j in enumerate(r().split())]
    # lines int: [R() for _ in range(n)]
    """

    if __name__ != '__main__':
        # for test
        sys.stdin = open('sample.txt')

    # ----------------------------------
    # main

    # N, K = R()
    # dp = [[[0]*3100 for _ in range(51)] for _ in range(51)]
    # dp[0][0][0] = 1
    # for i, rest, k in product(range(N), range(N), range(K+1)):
    #     if k % 2:
    #         continue
    #     dp[i+1][rest+1][k+2*rest+2] += dp[i][rest][k]
    #     dp[i+1][rest+1][k+2*rest+2] %= MOD
    #     # if rest:
    #     #     dp[i+1][rest][k+2*rest] += dp[i][rest][k] * 2 * rest
    #     #     dp[i+1][rest][k+2*rest] %= MOD
    #     dp[i+1][rest][k+2*rest] += dp[i][rest][k] * (2*rest+1)
    #     dp[i+1][rest][k+2*rest] %= MOD
    #     if rest:
    #         dp[i+1][rest-1][k+2*rest-2] += dp[i][rest][k] * rest * rest
    #         dp[i+1][rest-1][k+2*rest-2] %= MOD
    # print(dp[N][0][K])
    
    N, K = R()
    dp = [0]*2510*51*51
    ip = 2510*51
    restp = 2510
    dp[0] = 1
    for i, rest, k in product(range(N), range(N), range(0,K+1,2)):
        dp[(i+1)*ip+(rest+1)*restp+(k+2*rest+2)] += dp[i*ip+rest*restp+k]
        dp[(i+1)*ip+(rest+1)*restp+(k+2*rest+2)] %= MOD
        dp[(i+1)*ip+rest*restp+(k+2*rest)] += dp[i*ip+rest*restp+k] * (2*rest+1)
        dp[(i+1)*ip+rest*restp+(k+2*rest)] %= MOD
        if rest:
            dp[(i+1)*ip+(rest-1)*restp+(k+2*rest-2)] += dp[i*ip+rest*restp+k] * rest * rest
            dp[(i+1)*ip+(rest-1)*restp+(k+2*rest-2)] %= MOD
    print(dp[N*ip+K])
    
    # end of main
    # ----------------------------------

    """memo: how to use defaultdict of list
    # initialize
    Dic = defaultdict(list)
    # append / extend
    Dic[x].append(y)
    # for
    for k, v in Dic.items():
    """

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
md = 10 ** 9 + 7
if k % 2:
    print(0)
    exit()
k //= 2
dp = [[[0] * (n ** 2) for _ in range(n + 1)] for __ in range(n + 1)]
dp[0][0][0] = 1
for i in range(1, n + 1):
    dpi1 = dp[i - 1]
    for j in range(i + 1):
        for s in range(j, k + 1):
            # 片側、水平、両方上
            tmp = dpi1[j][s - j] * j * 2 + dpi1[j][s - j] + dpi1[j + 1][s - j] * (j + 1) ** 2
            if j:
                # 両方保留
                tmp += dp[i - 1][j - 1][s - j]
            dp[i][j][s] = tmp % md
print(dp[n][0][k])

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Your code here!
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline #文字列入力のときは注意

n,m = [int(i) for i in readline().split()]
MOD = 10**9+7

#dp[i][j][k]
# iまで見て j個未確定、k点
dp = [[[0 for k in range(n*n)] for j in range(n+1)] for i in range(n+1)]

dp[0][0][0] = 1

for i in range(n):
    for j in range(i+1):
        for k in range(n*n):
            if k + 2*j >= n*n: continue
            dp[i+1][j+1][k+2*j] += dp[i][j][k]
            dp[i+1][j+1][k+2*j] %= MOD
            dp[i+1][j  ][k+2*j] += (2*j+1)*dp[i][j][k]
            dp[i+1][j  ][k+2*j] %= MOD
            dp[i+1][j-1][k+2*j] += j*j*dp[i][j][k]
            dp[i+1][j-1][k+2*j] %= MOD
    

#print(*dp,sep="\n")

ans = dp[-1][0][m]
print(ans)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys
from itertools import product

MOD = 1000000007  # type: int

def solve(N: int, K: int):
    if K % 2 == 1:
        print(0)
        return
    dp = [[[0 for k in range(K+1)]
            for j in range(N+1)]
            for i in range(N+1)]
    dp[0][0][0] = 1
    for i, j, k in product(range(1, N+1), range(N+1), range(K+1)):
        prev_k = k - 2 * j
        if prev_k < 0:
            continue
        dp[i][j][k] += dp[i-1][j][prev_k]
        dp[i][j][k] += 2 * j * dp[i-1][j][prev_k]
        dp[i][j][k] += (j+1) * (j+1) * dp[i-1][j+1][prev_k]
        dp[i][j][k] += dp[i-1][j-1][prev_k]
        dp[i][j][k] %= MOD
    print(dp[N][0][K])

    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    n = int(next(tokens))  # type: int
    k = int(next(tokens))  # type: int
    solve(n, k)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import itertools
import os
import sys

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

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

N, K = list(map(int, sys.stdin.readline().split()))

if K % 2 == 1:
    print(0)
    exit()
if N == 1:
    if K == 0:
        print(1)
    else:
        print(0)
    exit()

# 解説AC
# dp[i][j][k]: i まで決まってて、保留の数が j、確定した奇妙さが k
dp = [[[0] * (K + 1) for _ in range(N)] for _ in range(N)]
# dp = np.zeros((N, N, K + 1), dtype=int)
dp[0][0][0] = 1
dp[0][1][2] = 1
for i, j, k in itertools.product(range(1, N), range(N - 1), range(K + 1)):
    if k - j * 2 < 0:
        continue
    # i == pi
    # 保留の数はそのまま
    # 奇妙さは保留の数だけ増える
    dp[i][j][k] += dp[i - 1][j][k - j * 2] * 1
    # i == p_j または j == p_i (j < i)
    # 保留の数はそのまま
    # 奇妙さは保留の数だけ増える
    # パターン数はうさぎの保留数j + かめの保留数j
    dp[i][j][k] += dp[i - 1][j][k - j * 2] * (j * 2)
    # i == p_j かつ j == p_j (j < i)
    # 保留数が1減る
    # パターン数はうさぎの保留数j * かめの保留数j
    dp[i][j][k] += dp[i - 1][j + 1][k - j * 2] * (j + 1) ** 2
    if j - 1 >= 0:
        # 両方保留
        # そのまま増やす
        dp[i][j][k] += dp[i - 1][j - 1][k - j * 2]

    dp[i][j][k] %= MOD
print(dp[-1][0][K])

Submission status: Runtime Error

Solution code:
import itertools
import os
import sys

import numpy as np

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

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

N, K = list(map(int, sys.stdin.readline().split()))

if K % 2 == 1:
    print(0)
    exit()

# 解説AC
# dp[i][j][k]: i まで決まってて、保留の数が j、確定した奇妙さが k
dp = np.zeros((N, N, K + 1), dtype=int)
dp[0][0][0] = 1
dp[0][1][2] = 1
for i, j, k in itertools.product(range(1, N), range(N - 1), range(K + 1)):
    if k - j * 2 < 0:
        continue
    # i == pi
    # 保留の数はそのまま
    # 奇妙さは保留の数だけ増える
    dp[i][j][k] += dp[i - 1][j][k - j * 2] * 1
    # i == p_j または j == p_i (j < i)
    # 保留の数はそのまま
    # 奇妙さは保留の数だけ増える
    # パターン数はうさぎの保留数j + かめの保留数j
    dp[i][j][k] += dp[i - 1][j][k - j * 2] * (j * 2)
    # i == p_j かつ j == p_j (j < i)
    # 保留数が1減る
    # パターン数はうさぎの保留数j * かめの保留数j
    dp[i][j][k] += dp[i - 1][j + 1][k - j * 2] * (j + 1) ** 2
    if j - 1 >= 0:
        # 両方保留
        # そのまま増やす
        dp[i][j][k] += dp[i - 1][j - 1][k - j * 2]

    dp[i][j][k] %= MOD
print(dp[-1][0][K])

Submission status: Runtime Error

Solution code:
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
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(): return list(sys.stdin.readline())[:-1]
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

#A
def A():
    n = I()
    print(3*n**2)
    return

#B
def B():
    n,d = LI()
    f = [1]*(n+2*d+2)
    ans = 0
    for i in range(n):
        if f[i]:
            for j in range(i,i+2*d+1):
                f[j] = 0
            ans += 1
    print(ans)
    return

#C
def C():
    n = I()
    a = IR(n)
    mi = max(a)
    if a.count(mi) > 1:
        for i in range(n):
            print(mi)
    else:
        b = [a[i] for i in range(n)]
        b.sort()
        b = b[::-1]
        for i in range(n):
            if mi != a[i]:
                print(mi)
            else:
                print(b[1])

    return

#D
def D():
    n = I()
    a = LI()
    b = [0]*(n+1)
    for i in range(1,n+1)[::-1]:
        j = 2*i
        k = 0
        while j <= n:
            k ^= b[j]
            j += i
        if a[i-1]^k:
            b[i] = 1
    ans = []
    for i in range(n+1):
        if b[i]:
            ans.append(i)
    print(len(ans))
    if ans:
        print(*ans)
    return

#E
def E():
    n = I()
    a = IR(n)
    mi = []
    ans = 0
    for i in range(n):
        j = bisect.bisect_right(mi,-a[i])
        if j == len(mi):
            mi.append(-a[i])
        else:
            mi[j] = -a[i]
    print(len(mi))
    return

#F 箱根駅伝DP
def F():
    n,K = LI()
    dp = [[[0]*(K+100) for j in range(n+1)] for i in range(n+1)] #dp[i][j][k] : i段目、j個保留の時にスコアがkとなるパターン数(保留した点の数だけ、スコアは加算されていく,保留点が段をまたいでスコアが増えていくイメージ)
    dp[0][0][0] = 1
    for i in range(n):
        for j in range(i+1):
            for k in range(K+1):
                #パターン1 : i+1段目で両方結ぶ
                nj = j
                dp[i+1][nj][k+2*nj] += dp[i][j][k]
                dp[i+1][nj][k+2*nj] %= mod
                #パターン2 : i+1段目で両方結ばない
                nj = j+1
                dp[i+1][nj][k+2*nj] += dp[i][j][k]
                dp[i+1][nj][k+2*nj] %= mod
                #パターン3 : i+1段目で片側ともう片方の保留点を結ぶ
                nj = j
                x = j*2 #結ぶ相方の選び方((右or左)*(保留点の数))
                dp[i+1][nj][k+2*nj] += dp[i][j][k]*x
                dp[i+1][nj][k+2*nj] %= mod
                #パターン4 : i+1段目で両側ともう片方の保留点を結ぶ
                nj = j-1
                x = j*j #結ぶ相方の選び方(左側の保留点*右側の保留点)
                dp[i+1][nj][k+2*nj] += dp[i][j][k]*x
                dp[i+1][nj][k+2*nj] %= mod
    print(dp[n][0][K])
    return

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