51nod--1242 斐波那契数列第N项 (矩阵乘法优化)

题目:

1242 斐波那契数列的第N项
基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 关注
斐波那契数列的定义如下:

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的结果。
Input示例
11
Output示例
89

分析:

一般我们数据小, 可以直接模拟递推过去, 这里 n 达到 10 ^ 18 很大, 时间, 空间都过不去了。
需要优化。

我们可以发现 Fn = Fn-1 + Fn-2的;
Fn = 1 1 * Fn-1
Fn-1 0 1 Fn-2
由此可构造矩阵了优化了。

实现:

#include <bits/stdc++.h>

using namespace std;

typedef long long LL;

const LL MOD = 1000000009;

struct Martix {
    LL data[2][2];

    Martix() {
        for(int i = 0; i < 2; ++i)
            for(int j = 0; j <2; ++j)
            data[i][j] = 0;
    }
    Martix(int a, int b, int c, int d) {
        data[0][0] = a;
        data[0][1] = b;
        data[1][0] = c;
        data[1][1] = d;
    }

    Martix operator * (const Martix a) const {
        Martix tmp;
        for(int i = 0; i < 2; ++i)
            for(int j = 0; j <2; ++j)
                for(int k = 0; k < 2; ++k)
                tmp.data[i][j] = (tmp.data[i][j] + this->data[i][k] * a.data[k][j] % MOD) % MOD;
        return tmp;
    }

    void Print() {
        cout << "Ma : \n";
        for(int i = 0; i < 2; ++i) {
            for(int j = 0; j < 2; ++j)
            cout << this->data[i][j] << " ";
            cout << endl;
        }
    }
};

const Martix E = Martix(1,0,0,1);
const Martix Be = Martix(1,1,1,0);

Martix Ma_Pow(Martix a, LL n) {
    Martix ret = E;
    while(n) {
        if(n & 1) ret = ret * a;
        a = a * a;
        n >>= 1;
    }
    return ret;
}

int main() {
    LL n;
    while(cin >> n) {
        if (n == 0) cout << 0 <<endl;
        else if (n == 1) cout << 1 << endl;
        else {
            Martix ans = Ma_Pow(Be, n-1);
            cout << ans.data[0][0] <<endl;
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值