洛谷题单指南-基础线性代数-P1349 广义斐波那契数列

原题链接:https://www.luogu.com.cn/problem/P1349

题意解读:求数列第n项。

解题思路:矩阵快速幂优化递推。

image

100分代码:

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

typedef long long LL;
LL p, q, a1, a2, n, m;

struct Matrix
{
    LL a[5][5];

    Matrix()
    {
        memset(a, 0, sizeof(a));
    }

    Matrix operator * (const Matrix &to) const
    {
        Matrix res;
        for(int i = 1; i <= 2; i++)
            for(int j = 1; j <= 2; j++)
                for(int k = 1; k <= 2; k++)
                    res.a[i][j] = (res.a[i][j] + a[i][k] * to.a[k][j]) % m;
        return res;
    }
} b2, A, ans;

Matrix ksm(Matrix &a, LL b)
{
    Matrix res;
    res.a[1][1] = 1, res.a[2][2] = 1;
    while(b)
    {
        if(b & 1) res = res * a;
        b >>= 1;
        a = a * a;  
    }
    return res;
}

int main()
{
    cin >> p >> q >> a1 >> a2 >> n >> m;
    if(n == 1) cout << a1;
    else if(n == 2) cout << a2;
    else
    {
        b2.a[1][1] = a2;
        b2.a[1][2] = a1;
        A.a[1][1] = p;
        A.a[2][1] = q;
        A.a[1][2] = 1;
        A.a[2][2] = 0;
        ans = b2 * ksm(A, n - 2);
        cout << ans.a[1][1];
    }
    return 0;
}

 

posted @ 2026-02-25 14:44  hackerchef  阅读(0)  评论(0)    收藏  举报