【数论】【矩阵加速】[POJ3070]Fibonacci

题目描述

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:

1, 1, 2, 3, 5, 8, 13, 21, 34, …

样例输入

0
9
999999999
1000000000
-1

样例输出

0
34
626
6875

题目分析

首先我们可以发现Fib的定义为

Fi=Fi1+Fi2
那么我们就有可以发现
[F2F1F1F0][1110]=[F3F2F2F1]
那么我们就有
[F2F1F1F0][1110][1110]=[F4F3F3F2]
那么我们可以发现
[1110][1110]=[F3F2F2F1]
[1110]n=[Fn+1FnFnFn1]
然后矩阵快速幂一下就好了

代码

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 5;
const int MOD = 10000;
struct Matrix {
    int Ma[MAXN+10][MAXN+10], n, m;
    void Clear(int u, int un=0, int um=0){
        n = un, m = um;
        for(int i=1;i<=un;i++)
            for(int j=1;j<=um;j++)
                Ma[i][j] = 0;
        if(u) for(int i=1;i<=un;i++)
            Ma[i][i] = 1;
    }
    Matrix operator* (const Matrix& ma) {
        Matrix ret ;
        ret.Clear(0, n, m);
        for(int i=1;i<=n;i++){
            for(int j=1;j<=ma.m;j++){
                for(int k=1;k<=ma.n;k++){
                    ret.Ma[i][j] += Ma[i][k] * ma.Ma[k][j];
                    ret.Ma[i][j] %= MOD;
                }
            }
        }
        return ret;
    }
};
Matrix Mpow(Matrix m, int p){
    Matrix ret;
    if(p == 0){
        ret.Clear(1, 2, 2);
        return ret;
    }else if(p == 1) return m;
    ret = Mpow(m, p/2);
    if(p%2 == 0) return ret * ret;
    return (ret * ret) * m;
}
int main(){
    int n;
    while(scanf("%d", &n) && ~n ){
        Matrix m;
        m.Clear(0, 2, 2);
        m.Ma[1][1] = 1;
        m.Ma[2][1] = 1;
        m.Ma[1][2] = 1;
        Matrix ans = Mpow(m, n);
        printf("%d\n", ans.Ma[1][2]);
    }

    return 0;
}

posted on 2016-03-01 13:37  JeremyGuo  阅读(132)  评论(0编辑  收藏  举报

导航