結果

問題 No.2503 Typical Path Counting Problem on a Grid
ユーザー suisensuisen
提出日時 2023-07-21 20:33:20
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 425 ms / 2,000 ms
コード長 1,408 bytes
コンパイル時間 367 ms
コンパイル使用メモリ 86,920 KB
実行使用メモリ 161,688 KB
最終ジャッジ日時 2023-10-13 18:07:17
合計ジャッジ時間 5,585 ms
ジャッジサーバーID
(参考情報)
judge15 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 275 ms
158,640 KB
testcase_01 AC 425 ms
161,004 KB
testcase_02 AC 311 ms
160,696 KB
testcase_03 AC 372 ms
161,652 KB
testcase_04 AC 372 ms
161,136 KB
testcase_05 AC 350 ms
161,080 KB
testcase_06 AC 353 ms
160,744 KB
testcase_07 AC 348 ms
160,928 KB
testcase_08 AC 334 ms
160,736 KB
testcase_09 AC 363 ms
161,688 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from typing import Tuple

P = 998244353

Matrix = Tuple[
    Tuple[int, int],
    Tuple[int, int]
]

def matrix_product(A: Matrix, B: Matrix) -> Matrix:
    ((a00, a01),
    (a10, a11)) = A

    ((b00, b01),
    (b10, b11)) = B

    return (
        ((a00 * b00 + a01 * b10) % P, (a00 * b01 + a01 * b11) % P),
        ((a10 * b00 + a11 * b10) % P, (a10 * b01 + a11 * b11) % P)
    )

def matrix_pow(A: Matrix, n: int):
    R: Matrix = (
        (1, 0),
        (0, 1)
    )
    while n:
        if n & 1:
            R = matrix_product(R, A)
        A = matrix_product(A, A)
        n >>= 1
    return R

def main(n: int, m: int):
    if n > m:
        n, m = m, n

    if n == 0:
        return 1
    
    fn1, fn = g[n - 1], g[n]

    A: Matrix = (
        (0, 1),
        (n, 2 * n + 1)
    )

    ((t00, t01),
    (t10, t11)) = matrix_pow(A, m - n)

    fm1, fm = (
        (t00 * fn1 + t01 * fn) % P,
        (t10 * fn1 + t11 * fn) % P
    )

    return (fm1 * fn1 % P * n + fm * fn) % P

if __name__ == '__main__':
    MAX_N = 10 ** 7
    g = [0] * (MAX_N + 1)
    g[0] = 1
    for i in range(1, MAX_N + 1):
        g[i] += g[i - 1] * 2 * i
        if i >= 2:
            g[i] += g[i - 2] * (i - 1)
        g[i] %= P

    T = int(input())

    answers = []

    for _ in range(T):
        n, m = map(int, input().split())
        answers.append(main(n, m))
    
    print('\n'.join(map(str, answers)))
0