結果

問題 No.1275 綺麗な式
ユーザー hiro71687k
提出日時 2024-11-06 00:27:02
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 18 ms / 2,000 ms
コード長 1,852 bytes
コンパイル時間 1,973 ms
コンパイル使用メモリ 193,864 KB
最終ジャッジ日時 2025-02-25 02:22:34
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 60
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

const int MOD = 1000000007;

// 2x2行列の構造体
struct Matrix {
    ll a11, a12, a21, a22;

    Matrix(ll _a11=1, ll _a12=0, ll _a21=0, ll _a22=1) : a11(_a11), a12(_a12), a21(_a21), a22(_a22) {}

    // 行列の乗算
    Matrix operator*(const Matrix& other) const {
        Matrix res;
        res.a11 = (a11 * other.a11 + a12 * other.a21) % MOD;
        res.a12 = (a11 * other.a12 + a12 * other.a22) % MOD;
        res.a21 = (a21 * other.a11 + a22 * other.a21) % MOD;
        res.a22 = (a21 * other.a12 + a22 * other.a22) % MOD;
        return res;
    }
};

// 行列累乗の高速化
Matrix power_matrix(Matrix base, ll power){
    Matrix result(1, 0, 0, 1); // 単位行列
    while(power > 0){
        if(power & 1){
            result = result * base;
        }
        base = base * base;
        power >>=1;
    }
    return result;
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    ll a, b, n;
    cin >> a >> b >> n;

    // n=0およびn=1の場合を個別に処理
    if(n == 0){
        cout << 2 % MOD;
        return 0;
    }
    if(n == 1){
        ll s1 = (2 * (a % MOD)) % MOD;
        cout << s1;
        return 0;
    }

    // 2a mod MODを計算
    ll two_a = (2 * (a % MOD)) % MOD;

    // (a^2 - b) mod MODを計算
    ll a_sq_mod = (a % MOD) * (a % MOD) % MOD;
    ll a_sq_minus_b = (a_sq_mod - (b % MOD) + MOD) % MOD;

    // 遷移行列を定義
    Matrix trans(two_a, (MOD - a_sq_minus_b) % MOD, 1, 0);

    // trans^(n-1)を計算
    Matrix trans_n_minus_1 = power_matrix(trans, n-1);

    // 初期ベクトル [S(1), S(0)] = [2a, 2]
    ll S1 = two_a;
    ll S0 = 2 % MOD;

    // S(n) = trans^(n-1) * [S1, S0]^T を計算
    ll Sn = (trans_n_minus_1.a11 * S1 + trans_n_minus_1.a12 * S0) % MOD;

    cout << Sn;
}
0