题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=148
/
题目的意思就是给个数n求fibonacci数列的第n项mod10000的结果,
显然要用到矩阵连乘,因为题中已经给出了解题思路,这里就不多说了,主要是算矩阵幂的时候用快速幂,
参考代码如下:
#include <iostream>
using namespace std;
class mat
{
public:
int m[2][2];
};
int mod;
mat operator*(mat a,mat b)
{
int i,j,k;
mat c;
for (i=0;i<2;i++)
{
for (j=0;j<2;j++)
{
c.m[i][j] = 0;
for (k=0;k<2;k++)
c.m[i][j]+=(a.m[i][k]*b.m[k][j])%mod;
c.m[i][j]%=mod;
}
}
return c;
}
mat operator^(mat a,int x)
{
mat p = a,q = a;
x--;
while (x>=1)
{
if(x%2==1)
p = p*q;
x/=2;
q = q*q;
}
return p;
}
int main()
{
int n;
mod=10000;
while(cin>>n&&n!=-1)
{
if(n==0)
{
cout<<0<<endl;
continue;
}
if(n==1||n==2)
{
cout<<1<<endl;
continue;
}
mat c;
mat a;
a.m[0][0]=a.m[0][1]=a.m[1][0]=1;
a.m[1][1]=0;
c=a^(n-2);
int ans=(c.m[0][0]+c.m[1][0])%10000;
cout<<ans<<endl;
}
return 0;
}