結果

問題 No.526 フィボナッチ数列の第N項をMで割った余りを求める
ユーザー boutarouboutarou
提出日時 2020-09-22 10:01:16
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 1,189 bytes
コンパイル時間 1,591 ms
コンパイル使用メモリ 171,128 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-08 03:31:00
合計ジャッジ時間 2,463 ms
ジャッジサーバーID
(参考情報)
judge11 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,376 KB
testcase_01 AC 1 ms
4,376 KB
testcase_02 AC 2 ms
4,380 KB
testcase_03 AC 2 ms
4,376 KB
testcase_04 AC 2 ms
4,376 KB
testcase_05 AC 2 ms
4,376 KB
testcase_06 AC 1 ms
4,380 KB
testcase_07 AC 2 ms
4,376 KB
testcase_08 AC 2 ms
4,376 KB
testcase_09 AC 2 ms
4,376 KB
testcase_10 AC 1 ms
4,380 KB
testcase_11 AC 2 ms
4,376 KB
testcase_12 AC 2 ms
4,376 KB
testcase_13 AC 1 ms
4,376 KB
testcase_14 AC 2 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)n;i++)
using namespace std;
using ll = long long;
using P = pair<int, int>;
using vec = vector<ll>;
using mat = vector<vec>;

ll MOD;
int msize; // 遷移行列のサイズ

// DPの更新
vec matmul(vec &dp, mat &mt) {
    vec ret(msize, 0);
    rep(i, msize) {
        rep(j, msize) {
            ret[i] += mt[i][j] * dp[j] % MOD;
            ret[i] %= MOD;
        }
    }
    return ret;
}

// 遷移行列の更新(2乗)
mat update(mat &mt) {
    mat ret(msize, vec(msize, 0));
    rep(i, msize) {
        rep(j, msize) {
            rep(k, msize) {
                ret[i][j] += mt[i][k] * mt[k][j] % MOD;
                ret[i][j] %= MOD;
            }
        }
    }
    return ret;
}

// mt ** k * dp
void matpow(vec &dp, mat &mt, int k) {
    msize = dp.size();
    while(k) {
        if (k & 1) dp = matmul(dp, mt);
        mt = update(mt);
        k /= 2;
    }
}

int main() {
    ll n, m;
    cin >> n >> m;
    MOD = m;

    vec dp(2);
    mat mt(2, vec(2));

    dp[0] = 0, dp[1] = 1;
    mt[0][0] = mt[0][1] = mt[1][0] = 1, mt[1][1] = 0;

    matpow(dp, mt, n);
    cout << dp[1] << endl;
    return 0;
}
0