这道题的思路与 P1962 斐波那契数列 基本一致,推出矩阵,然后快速幂即可
#include<bits/stdc++.h>
using namespace std;
int T,n;
const int mod=1e9+7;
struct juzhen
{
long long a[4][4];
}ans,fore,temp;
juzhen mul(juzhen xa, juzhen xb)
{
juzhen cnt;
for(int i=1;i<=3;i++)
for(int j=1;j<=3;j++)
{
long long tmp=0;
for(int k=1;k<=3;k++)
tmp+=(xa.a[i][k]*xb.a[k][j])%mod,tmp%=mod;
cnt.a[i][j]=tmp;
}
return cnt;
}
juzhen pow(long long x)
{
if(x==0)
{
return temp;
}
if(x==1)
{
return fore;
}
if(x%2==1)
{
juzhen xa=pow((x-1)/2);
return mul(mul(xa,xa),fore);
}
else
{
juzhen xa=pow(x/2);
return mul(xa,xa);
}
}
int main()
{
scanf("%d",&T);
for(int i=1;i<=3;i++) for(int j=1;j<=3;j++) fore.a[i][j]=0;
fore.a[1][3]=fore.a[2][1]=fore.a[3][2]=fore.a[3][3]=1;
for(int i=1;i<=3;i++) for(int j=1;j<=3;j++) temp.a[i][j]=0;
temp.a[1][1]=temp.a[2][2]=temp.a[3][3]=1;
while(T--)
{
scanf("%d",&n);
ans=pow(n-1);
printf("%lld\n",(ans.a[1][1]+ans.a[2][1]+ans.a[3][1])%mod);
}
return 0;
}

本文介绍了一种使用矩阵快速幂的方法来高效求解斐波那契数列的问题。通过构建特定矩阵并利用快速幂运算,可以大幅提高计算斐波那契数列第n项的速度,尤其在n值较大时优势明显。
312

被折叠的 条评论
为什么被折叠?



