POJ3070 Fibonacci[矩阵乘法]【学习笔记】

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

.

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


矩阵乘法的应用
一个有趣的理解:
结果矩阵第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=0,f=1;
    while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    return x*f;
}
int n;
struct mat{
    int r,c;
    int m[3][3];
    mat(){r=2;c=2;memset(m,0,sizeof(m));}
}im,f;
mat mult(mat x,mat y){
    mat t;
    for(int i=1;i<=x.r;i++)
        for(int k=1;k<=x.c;k++) if(x.m[i][k])
            for(int j=1;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=1;i<=im.c;i++)
        for(int j=1;j<=im.r;j++)
            if(i==j) im.m[i][j]=1;
    f.m[1][1]=1;f.m[1][2]=1;
    f.m[2][1]=1;f.m[2][2]=0;
}
int main(){
    init();
    while((n=read())!=-1){
        mat ans=im,t=f;
        for(;n;n>>=1,t=mult(t,t))
            if(n&1) ans=mult(ans,t);
        printf("%d\n",ans.m[1][2]); 
    }
}

 

posted @ 2016-10-23 19:55  Candy?  阅读(334)  评论(0编辑  收藏  举报