POJ3070 Fibonacci[矩阵乘法]

时间:2022-07-02 00:17:45
Fibonacci
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 13677   Accepted: 9697

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

POJ3070 Fibonacci[矩阵乘法].

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

POJ3070 Fibonacci[矩阵乘法].

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

POJ3070 Fibonacci[矩阵乘法].

Source


矩阵乘法的应用
一个有趣的理解:
结果矩阵第m行与第n列交叉位置的那个值,等于第一个矩阵第m行与第二个矩阵第n列,对应位置的每个值的乘积之和
白书上的一句:
把一个向量v变成另一个向量v1,并且v1的每一个分量都是v各个分量的线性组合,考虑使用矩阵乘法
对于斐波那契数列,构造矩阵
1 1
1 0
然后
让矩阵
A     1 1
B     1 0
相乘,就是得到
A+B
A
就是斐波那契数列啊
快速幂来优化到logn
遇到一个n很大的DP/递推关系,都可以考虑用这种方法
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int MOD=1e4;
typedef long long ll;
inline int read(){
char c=getchar();int x=,f=;
while(c<''||c>''){if(c=='-')f=-;c=getchar();}
while(c>=''&&c<=''){x=x*+c-'';c=getchar();}
return x*f;
}
int n;
struct mat{
int r,c;
int m[][];
mat(){r=;c=;memset(m,,sizeof(m));}
}im,f;
mat mult(mat x,mat y){
mat t;
for(int i=;i<=x.r;i++)
for(int k=;k<=x.c;k++) if(x.m[i][k])
for(int j=;j<=y.c;j++)
t.m[i][j]=(t.m[i][j]+x.m[i][k]*y.m[k][j]%MOD)%MOD;
return t;
}
void init(){
for(int i=;i<=im.c;i++)
for(int j=;j<=im.r;j++)
if(i==j) im.m[i][j]=;
f.m[][]=;f.m[][]=;
f.m[][]=;f.m[][]=;
}
int main(){
init();
while((n=read())!=-){
mat ans=im,t=f;
for(;n;n>>=,t=mult(t,t))
if(n&) ans=mult(ans,t);
printf("%d\n",ans.m[][]);
}
}