結果

問題 No.2503 Typical Path Counting Problem on a Grid
ユーザー 👑 emthrmemthrm
提出日時 2023-07-24 20:41:49
言語 C++23
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 217 ms / 2,000 ms
コード長 1,802 bytes
コンパイル時間 1,193 ms
コンパイル使用メモリ 85,416 KB
実行使用メモリ 42,608 KB
最終ジャッジ日時 2023-10-13 18:07:25
合計ジャッジ時間 3,592 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 123 ms
42,420 KB
testcase_01 AC 161 ms
42,476 KB
testcase_02 AC 165 ms
42,424 KB
testcase_03 AC 182 ms
42,440 KB
testcase_04 AC 210 ms
42,492 KB
testcase_05 AC 181 ms
42,444 KB
testcase_06 AC 217 ms
42,424 KB
testcase_07 AC 216 ms
42,384 KB
testcase_08 AC 198 ms
42,384 KB
testcase_09 AC 211 ms
42,608 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <array>
#include <cassert>
#include <cstdint>
#include <iostream>

#include <atcoder/modint>

// <AC>
// 解説通り
int main() {
  using mint = atcoder::modint998244353;
  constexpr int kMaxT = 20000, kMaxN = 10000000;
  constexpr std::int64_t kMaxM = 1000000000000000000;

  using Matrix = std::array<std::array<mint, 2>, 2>;
  const auto Pow = [](const Matrix& x, std::int64_t exponent) -> Matrix {
    const auto Mult = [](const Matrix& x, const Matrix& y) -> Matrix {
      Matrix res{0, 0, 0, 0};
      for (int i = 0; i < 2; ++i) {
        for (int k = 0; k < 2; ++k) {
          for (int j = 0; j < 2; ++j) {
            res[i][j] += x[i][k] * y[k][j];
          }
        }
      }
      return res;
    };
    Matrix res{1, 0, 0, 1}, tmp = x;
    for (; exponent > 0; exponent /= 2) {
      if (exponent % 2 == 1) res = Mult(res, tmp);
      tmp = Mult(tmp, tmp);
    }
    return res;
  };

  // 前計算
  std::array<mint, kMaxN + 1> dp{};
  dp[0] = 1;
  for (int i = 0; i < kMaxN; ++i) {
    dp[i + 1] += dp[i] * (i + 1) * 2;
    if (i + 2 <= kMaxN) dp[i + 2] += dp[i] * (i + 1);
  }

  int t;
  std::cin >> t;
  assert(1 <= t && t <= kMaxT);

  while (t--) {
    int n;
    std::int64_t m;
    std::cin >> n >> m;
    assert(0 <= n && n <= kMaxN && 0 <= m && m <= kMaxM);
    if (n > m) {
      const int tmp = m;
      m = n;
      n = tmp;
    }
    if (n == 0) {
      std::cout << 1 << '\n';
      continue;
    }

    const Matrix matrix = Pow(Matrix{n * 2 + 1, n, 1, 0}, m - n);
    const mint f_m =
        matrix[0][0] * dp[n] + matrix[0][1] * dp[n - 1];  // f(m)
    const mint f_m_1 =
        matrix[1][0] * dp[n] + matrix[1][1] * dp[n - 1];  // f(m - 1)
    const mint ans = f_m * dp[n] + f_m_1 * dp[n - 1] * n;
    std::cout << ans.val() << '\n';
  }
  return 0;
}
0