? 题目链接:http://poj.org/problem?id=3070 ?
这题就是让求斐波那契数列的第n项,但是题目中n很大,所以打表和直接求都会TLE,对于这个题我们可以用矩阵快速幂,下面一张图片详细解释过程:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define mod 10000
using namespace std;
typedef long long LL;
const int Max_n=100005;
struct Mat{
int mat[2][2];
};
Mat mul(Mat a,Mat b){
Mat ans;
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
ans.mat[i][j]=0;
for(int k=0;k<2;k++)
ans.mat[i][j]+=(a.mat[i][k]*b.mat[k][j])%mod;
ans.mat[i][j]%=mod;
}
}
return ans;
}
Mat q_pow(Mat a,int b){
Mat ans={1,0,0,1};
Mat res=a;
while(b){
if(b&1) ans=mul(ans,res);
res=mul(res,res);
b>>=1;
}
return ans;
}
int main(){
int n;
while(~scanf("%d",&n)&&n!=-1){
Mat a={1,1,1,0};
Mat ans={0,0,0,0};
ans=q_pow(a,n);
printf("%d\n",ans.mat[0][1]);
}
return 0;
}