[luogu] 斐波那契数列

Posted xayata

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[luogu] 斐波那契数列相关的知识,希望对你有一定的参考价值。

https://www.luogu.org/problemnew/show/P1962

矩阵快速幂加速

#include <bits/stdc++.h>

using namespace std;

#define gc getchar()
#define LL long long

const LL mod = 1000000007;

LL n, s;

inline LL read(){
    LL x = 0; char c = gc;
    while(c < 0 || c > 9) c = gc;
    while(c >= 0 && c <= 9) x = x * 10 + c - 0, c = gc;
    return x;
}

struct Node{
    LL m[3][3];
    Node() { memset(m,0,sizeof m);}
    void clear(){for(int i = 1; i <= n; i ++) m[i][i] = 1;}
};

Node operator *(Node a, Node b){
    Node ret;
    for(int i = 1; i <= n; i ++)
        for(int j = 1; j <= n; j ++)
            for(int k = 1; k <= n; k ++)
                ret.m[i][j] = (ret.m[i][j] + a.m[i][k] * b.m[k][j]) % mod;
    return ret;
}

Node ksm(Node a, LL p){
    Node ret; ret.clear();    
    while(p){
        if(p & 1) ret = ret * a;
        a = a * a;
        p >>= 1;
    }
    return ret;
}

int main()
{
     s = read();
    n = 2;
    Node a, b;
    a.m[1][1] = 0; a.m[1][2] = 1; a.m[2][1] = 1; a.m[2][2] = 1;
    b.m[1][1] = 1; b.m[2][1] = 1;
    Node Ans;
    Ans = ksm(a, s - 1);
    Node answer = Ans * b;
    cout << answer.m[1][1];

    return 0;
}

 

以上是关于[luogu] 斐波那契数列的主要内容,如果未能解决你的问题,请参考以下文章

[luogu] 斐波那契数列

洛谷P1962 斐波那契数列

洛谷—— P1962 斐波那契数列

P2626 斐波那契数列(升级版) 洛谷(2626)

08《算法入门教程》递归算法之斐波那契数列

Luogu P3938 斐波那契