每日模板一练——矩阵快速幂
打个模板防止手生了吧。。。
大意:求Febnaci第n项(n<=1e9)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int MOD=1e4;
LL n;
struct matrix{
int a[2][2];
matrix(int t=0)
{
memset(a,0,sizeof(a));
a[0][0]=a[1][1]=t;
}
friend inline matrix operator+(const matrix &x,const matrix &y){
matrix c;
for(int i=0;i<2;++i)
for(int j=0;j<2;++j)
c.a[i][j]=(x.a[i][j]+y.a[i][j])%MOD;
return c;
}
friend inline matrix operator*(const matrix &x,const matrix &y){
matrix c;
for(int i=0;i<2;++i)
for(int k=0;k<2;++k)
for(int j=0;j<2;++j)
c.a[i][j]=(c.a[i][j]+(x.a[i][k]*y.a[k][j]))%MOD;
return c;
}
friend inline matrix operator^(matrix aa,LL b){
matrix c(1);
while(b)
{
if(b&1)
c=c*aa;
b>>=1;
aa=aa*aa;
}
return c;
}
}base;
LL Read()
{
LL i=0,f=1;
char c;
for(c=getchar();(c>'9'||c<'0')&&c!='-';c=getchar());
if(c=='-')
f=-1,c=getchar();
for(;c>='0'&&c<='9';c=getchar())
i=(i<<3)+(i<<1)+c-'0';
return i*f;
}
int main()
{
base.a[0][0]=0,base.a[0][1]=1,base.a[1][0]=1,base.a[1][1]=1;
n=Read();
while(n!=-1)
{
if(n==0)
puts("0");
else
{
matrix x=(base^(n-1)); //人懒不想开ans矩阵
printf("%d\n",x.a[1][1]);
}
n=Read();
}
return 0;
}