POJ3070 Fibonacci[矩陣乘法]【學習筆記】

Candy?發表於2016-10-23
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]); 
    }
}

 

相關文章