• 51nod1242斐波那契数列的第N项 【矩阵快速幂】


    斐波那契数列的定义如下:

    F(0) = 0

    F(1) = 1

    F(n) = F(n - 1) + F(n - 2) (n >= 2)

    (1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, ...)

    给出n,求F(n),由于结果很大,输出F(n) % 1000000009的结果即可。

    Input

    输入1个数n(1 <= n <= 10^18)。

    Output

    输出F(n) % 1000000009的结果。

    Sample Input

    11

    Sample Output

    89

    思路:一道矩阵快速幂的模板题,这两天写一个博客再更新次题解。

    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    const int MOD=1000000009;
    struct mat
    {
        ll a[2][2];
    };
    mat mat_mul(mat x,mat y)
    {
        mat res;
        memset(res.a,0,sizeof(res.a));
        for(int i=0;i<2;i++)
            for(int j=0;j<2;j++)
            for(int k=0;k<2;k++)
            res.a[i][j]=(res.a[i][j]+x.a[i][k]*y.a[k][j])%MOD;
        return res;
    }
    void mat_pow(ll n)
    {
        mat c,res;
        c.a[0][0]=c.a[0][1]=c.a[1][0]=1;
        c.a[1][1]=0;
        memset(res.a,0,sizeof(res.a));
        for(int i=0;i<2;i++) res.a[i][i]=1;
        while(n)
        {
            if(n&1) res=mat_mul(res,c);
            c=mat_mul(c,c);
            n=n>>1;
        }
        printf("%I64d
    ",res.a[0][1]);
    }
    int main()
    {
        ll n;
        scanf("%lld",&n);
        mat_pow(n);
        return 0;
    }
  • 相关阅读:
    LeetCode(122. 买卖股票的最佳时机 II)
    LeetCode(485. 最大连续1的个数)

    约瑟夫问题
    链表
    队列
    稀疏数组
    乐优商城项目学习
    LeetCode_Climbing Stairs
    数据结构&&算法基础知识
  • 原文地址:https://www.cnblogs.com/aerer/p/9930937.html
Copyright © 2020-2023  润新知