当前位置: 代码迷 >> 综合 >> CF 450 B Jzzhu and Sequences(矩阵快速幂)
  详细解决方案

CF 450 B Jzzhu and Sequences(矩阵快速幂)

热度:96   发布时间:2023-12-08 11:13:32.0

题目链接:
CF 450 B Jzzhu and Sequences
分析:
Fibonacci数列裸题。只需要注意负数即可。

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;const long long mod=(long long)(1e9)+7;long long a,b,n;struct Matrix{int size;long long data[3][3];
};void init(Matrix& x,int size)
{x.size=size;memset(x.data,0,sizeof(x.data));
}void unit(Matrix& x)
{for(int i=1;i<=x.size;i++){ x.data[i][i]=1; }
}Matrix multiply(Matrix& x,Matrix& y)
{Matrix ans;init(ans,x.size);for(int i=1;i<=x.size;i++){for(int j=1;j<=x.size;j++){for(int k=1;k<=x.size;k++){ans.data[i][j]+=x.data[i][k]*y.data[k][j];ans.data[i][j]=(ans.data[i][j]+mod)%mod;//ans.data[i][j]%=mod;}}}return ans;
}Matrix quick_power(Matrix& x,long long m)
{Matrix ans,tmp=x;init(ans,x.size);unit(ans);while(m){if(m&1){ans=multiply(ans,tmp);}tmp=multiply(tmp,tmp);m>>=1;}return ans;
}int main()
{//freopen("in.txt","r",stdin);while(~scanf("%I64d %I64d",&a,&b)){scanf("%I64d",&n);if(n==1){printf("%I64d\n",(a+mod)%mod);continue;}else if(n==2){printf("%I64d\n",(b+mod)%mod);continue;}Matrix ans;ans.size=2;ans.data[1][1]=0;ans.data[1][2]=-1;ans.data[2][1]=ans.data[2][2]=1;ans=quick_power(ans,n-2);/*printf("ans:");for(int i=1;i<=2;i++){for(int j=1;j<=2;j++){printf("%I64d ",ans.data[i][j]);}}printf("\n");*/printf("%I64d\n",((a*ans.data[1][2]+b*ans.data[2][2])%mod+mod)%mod);//注意负数}
}
  相关解决方案