题目地址:http://poj.org/problem?id=3070

思路:矩阵快速幂和快速幂的思想差不多,按照下面2张图来就行

POJ 3070 Fibonacci(矩阵快速幂)_快速幂

POJ 3070 Fibonacci(矩阵快速幂)_快速幂_02

AC代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
const int inf = 0x3f3f3f3f;//1061109567
typedef long long ll;
const int maxn = 40000;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
struct node
{
int a[2][2];
void init()
{
a[0][0] = a[0][1] = a[1][0] = 1;
a[1][1] = 0;
}
};
node matrixmul(node a,node b)
{
node c;
for(int i=0; i<2; i++)
{
for(int j=0; j<2; j++)
{
c.a[i][j] = 0;
for(int k=0; k<2; k++)
{
c.a[i][j] += a.a[i][k] * b.a[k][j];
}
c.a[i][j] %= 10000;
}
}
return c;
}
node quickmod(node s,int k)
{
node ans;
ans.init();
while(k)
{
if(k & 1)
ans = matrixmul(ans,s);
k = k >> 1;
s = matrixmul(s,s);
}
return ans;
}
int main()
{
int n;
while(scanf("%d",&n))
{
if(n == -1)
break;
if(n == 0)
{
printf("0\n");
continue;
}
node s;
s.init();
s = quickmod(s,n-1);
printf("%d\n",s.a[0][1]%10000);
}
return 0;
}