@xunuo
2017-03-25T03:43:32.000000Z
字数 1541
阅读 1481
Time Limit: 1000MS Memory Limit: 65536K
矩阵快速幂
In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
An alternative formula for the Fibonacci sequence is

Given an integer n, your goal is to compute the last 4 digits of Fn.
The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.
For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).
0
9
999999999
1000000000
-1
0
34
626
6875
As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by

Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:

题意:
Fibonacci数列,问你第n个是多少?
解题思路:
由题+图可知:裸的矩阵快速幂,再取个模;模板模板,一切都是模板。。。。。
完整代码:
#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;const int mod=10000;struct node{int a[2][2];void init(){a[0][0]=0,a[0][1]=1;a[1][0]=1,a[1][1]=1;}};node matrixmul(node x,node y){node z;for(int i=0;i<2;i++)///题中为2*2的矩阵{for(int j=0;j<2;j++){z.a[i][j]=0;for(int k=0;k<2;k++)z.a[i][j]+=(x.a[i][k]*y.a[k][j]);///矩阵乘法z.a[i][j]%=mod;}}return z;}node mul(node s,int k){node ans;ans.init();while(k>=1){if(k&1)ans=matrixmul(ans,s);k>>=1;s=matrixmul(s,s);}return ans;}int main(){int n;while(scanf("%d",&n)!=EOF){int ans;if(n==-1)break;if(n==0)ans=0;else{node s;s.init();s=mul(s,n-1);ans=s.a[0][1]%mod;}printf("%d\n",ans);}return 0;}
