跳到正文

题解

P1349 广义斐波那契数列——矩阵加速——题解

longyitongxue约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月11日
篇幅
约 5 分钟
获赞
4
题目
P1349

版本

  1. v1当前

题目传送门

主要思路

70 pts 思路

无非就是按照递推式来一步步递推。这里不详细讲了。

70 pts \ 代码
C++
#include<iostream>
using namespace std;
int a[2147483648];
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr),cout.tie(nullptr);
    int p,q,n,m;
    cin>>p>>q>>a[1]>>a[2]>>n>>m;
    for(int i=3;i<=n;i++){
        a[i]=(p*a[i-1]+q*a[i-2])%m;
    }
    cout<<a[n];
    return 0;
}

100 pts 思路

我们考虑矩阵加速。根据正常的 Fibonacci,我们需要求出一个矩阵 [FnFn−1]\begin{bmatrix}F_n & F_{n-1}\end{bmatrix}。跟 Fibonacci 一样,我们需要根据 [Fn−1Fn−2]\begin{bmatrix}F_{n-1} & F_{n-2}\end{bmatrix} 来推出 [FnFn−1]\begin{bmatrix}F_n & F_{n-1}\end{bmatrix}。我们想想,如何用 [Fn−1Fn−2]\begin{bmatrix}F_{n-1} & F_{n-2}\end{bmatrix} 来推出 [FnFn−1]\begin{bmatrix}F_n & F_{n-1}\end{bmatrix} 呢?其实很简单。新矩阵中的 Fn−1F_{n-1} 可以直接从原来的矩阵给保留了下来,所以不难推出转移矩阵的第二列为 [10]\begin{bmatrix}1\\0\end{bmatrix}。对于 FnF_n ,我们已经知道 Fn=Fn−1×p+Fn−2×qF_n=F_{n-1}\times p+F_{n-2}\times q,所以转移矩阵的第一列就应该为 [pq]\begin{bmatrix}p\\q\end{bmatrix}。所以整个转移矩阵就应该为 [p1q0]\begin{bmatrix}p&1\\q&0\end{bmatrix}。那么,这道题的答案就出来了:[FnFn−1]=[F2F1]×[p1q0]n−2\begin{bmatrix}F_n & F_{n-1}\end{bmatrix}=\begin{bmatrix}F_2 & F_1\end{bmatrix}\times\begin{bmatrix}p&1\\q&0\end{bmatrix}^{n-2}。知道这个这道题就可以直接秒了!

WARNING

要特判,不然会被 hack 掉。

100 pts \ 代码
C++
#include<bits/stdc++.h>
using namespace std;
struct node{
    int arr[2][2];
    node(){memset(arr,0,sizeof arr);}
}f,dw;
int m;
node operator*(const node& x,const node& y){
    node t;
    for(int i=0;i<2;i++){
        for(int j=0;j<2;j++){
            t.arr[i][j]=0;
            for(int k=0;k<2;k++){
                t.arr[i][j]=(t.arr[i][j]+1ll*x.arr[i][k]*y.arr[k][j])%m;
            }
        }
    }
    return t;
}
node qpow(node a,int b){
    node ans;
    ans.arr[0][0]=ans.arr[1][1]=1;
    while(b){
        if(b&1)ans=ans*a;
        a=a*a;
        b>>=1;
    }
    return ans;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr),cout.tie(nullptr);
    int p,q,n;
    cin>>p>>q>>f.arr[0][1]>>f.arr[0][0]>>n>>m;//这里注意先读入[0][1]再读入[0][0]!!!
    if(n==1){
        cout<<f.arr[0][1]%m;
        return 0;
    }else if(n==2){
        cout<<f.arr[0][0]%m;
        return 0;
    }
    dw.arr[0][0]=p,dw.arr[0][1]=1,
    dw.arr[1][0]=q,dw.arr[1][1]=0;
    dw=qpow(dw,n-2);
    node ans=f*dw;
    cout<<ans.arr[0][0]%m;
    return 0;
}
原文