矩阵快速幂–Fibonacci POJ3070
题目连接
Fibonacci
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 17587 Accepted: 12257
Description
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.
Input
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.
Output
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).
Sample Input
0
9
999999999
1000000000
-1
Sample Output
0
34
626
6875
Hint
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:
Source
Stanford Local 2006
解题思路
显然用递归定义肯定不行,即使将递归转化成递推优化10^18也会超时,所以用到矩阵来转化
1.显然常规递推时间复杂度和空间复杂度都会超
2.当遇到这种问题时显然是找公式和规律
3.比如f[1][1]=1,f[n][m]=a*f[n-1][m]+b*f[n-1][m-1]当n和m超级大时,显然要利用公式,找出了杨辉三角
4.进而找出了快速幂求模,组合快速幂求模等
5.这道题没有公式这是用矩阵快速幂来解决递推无限大问题
#include<iostream>
#include<memory.h>
#include<stdio.h>
#define N 2
using namespace std;
typedef long long LL;
LL p=1000000009;
LL res[N][N];
void mult(LL res[][N],LL a[][N]){
LL tem[N][N];
memset(tem,0,sizeof(tem));
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
for(int k=0;k<N;k++){
tem[i][j]+=(res[i][k]*a[k][j])%p;
}
}
}
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
res[i][j]=tem[i][j];
}
}
return;
}
void quick_mod(LL a[][N],LL n){
memset(res,0,sizeof(res));
for(int i=0;i<N;i++){
res[i][i]=1;
}
while(n){
if(n&1){
mult(res,a);
}
mult(a,a);
n>>=1;
}
return;
}
int main(){
LL n;
LL a[2][2]={{1,1},{1,0}};
cin>>n;
quick_mod(a,n-1);
cout<<res[0][0]%1000000009<<endl;
return 0;
}