結果

問題 No.718 行列のできるフィボナッチ数列道場 (1)
ユーザー とばりとばり
提出日時 2018-07-27 23:52:05
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 1,738 bytes
コンパイル時間 1,368 ms
コンパイル使用メモリ 69,940 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-18 15:38:25
合計ジャッジ時間 1,837 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ(β)

テストケース

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

ソースコード

diff #

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

using int64 = long long;

const int64 MOD = 1e9 + 7;

template <typename T>
struct Matrix {
    const int M;
    const int N;
    std::vector<std::vector<T>> elts;

    Matrix(int m, int n, T v = 0) : M(m), N(n), elts(M, std::vector<T>(N, v)) {}

    template <class InputIt>
    Matrix(int m, int n, InputIt first, InputIt last)
        : M(m), N(n), elts(M, std::vector<T>(N)) {
        for (int i = 0; i < M; i++) {
            std::copy(first + (i * n), first + ((i + 1) * n), elts[i].begin());
        }
    }

    const std::vector<T>& operator[](int m) const { return elts[m]; } 

    Matrix operator*(const Matrix& m) const {
        Matrix res(M, m.N, 0);
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < m.N; j++) {
                for (int k = 0; k < N; k++) {
                    (res.elts[i][j] += (elts[i][k] * m.elts[k][j]) % MOD) %= MOD;
                }
            }
        }
        return res;
    }

    Matrix identity() {
         Matrix m(N, N, 0);
         for (int i = 0; i < N; i++) m.elts[i][i] = 1;
         return m;
    }

    Matrix pow(int64 n) {
        if (n == 0) { return identity(); }
        else if (n % 2 == 1) { return *this * pow(n - 1); }
        else { Matrix m = pow(n / 2); return m * m; }
    }
};

int main() {
    int64 N;
    cin >> N;

    vector<int64> x{ 1, 0, 0, 1 },
                  A{ 1, 1, 2, 0,
                     1, 0, 0, 0,
                     1, 0, 1, 0,
                     1, 1, 2, 1 };
    Matrix<int64> xm(4, 1, x.begin(), x.end());
    Matrix<int64> Am(4, 4, A.begin(), A.end());

    auto bm = Am.pow(N - 1) * xm;
    cout << bm[3][0] << endl;

    return 0;
}
0