POJ3070 斐波那契数列 矩阵快速幂

时间:2021-04-04 19:26:58

题目链接:http://poj.org/problem?id=3070

题意就是让你求斐波那契数列,不过n非常大,只能用logn的矩阵快速幂来做了

刚学完矩阵快速幂刷的水题,POJ不能用万能头文件是真的烦

#include<iostream>
#include<string.h>
#include<cmath>
#include<cstdio>
using namespace std;
typedef long long ll;
const int inf=<<;
const int maxn=1e5+;
const double pi=acos(-);
const int mod=;
struct matrix{
ll a[][]; //begin with 1
int r,c;
matrix(int n,int m):r(n),c(m){memset(a,,sizeof(a));}
ll* operator[](int x){return a[x];}
friend matrix operator*(matrix A,matrix B)
{
matrix C(A.r,B.c);
for(int i=;i<=A.r;i++)
for(int j=;j<=B.c;j++)
for(int k=;k<=A.c;k++){
C[i][j]+=(A[i][k]*B[k][j])%mod;
C[i][j]+=mod;
C[i][j]%=mod;
}
return C;
}
}; matrix qpow(matrix A,ll m)//方阵A的m次幂
{
matrix ans(A.r,A.c);
for(int i=;i<=A.r;i++) ans.a[i][i]=; //单位矩阵
while(m)
{
if(m&)ans=ans*A;
A=A*A;
m>>=;
}
return ans;
}
/*inline void read(ll &x){
char ch=x=0;
while(!isdigit(ch))
ch=getchar();
while(isdigit(ch))
x=x*10+ch-'0',ch=getchar();
}*/
int main(){
ll n;
while(~scanf("%lld",&n)){
if(n==-)break;
if(n==){
cout<<<<endl;continue;
}
matrix a(,);
a[][]=,a[][]=,a[][]=,a[][]=;
matrix x1(,);
x1[][]=,x1[][]=;
matrix ans=qpow(a,n-)*x1;//0cout<<233<<endl;
printf("%d\n",ans[][]%);
}
return ;
}