洛谷 P1962 斐波那契数列

洛谷 P1962 斐波那契数列

Description

  • 大家都知道,斐波那契数列是满足如下性质的一个数列:

    • f(1) = 1

    • f(2) = 1

    • f(n) = f(n-1) + f(n-2) (n ≥ 2 且 n 为整数)

    请你求出 f(n) mod 1000000007 的值。

Input

  • 第 1 行:一个整数 n

Output

  • 第 1 行: f(n) mod 1000000007 的值

Sample Input

10

Sample Output

55

Data Size

对于 100% 的数据: n在long long(INT64)范围内。

题解:

  • 矩阵加速。写这题前务必看过这篇
  • 推导过程:

o_e1708a256001c3b9a75262db3ac4aa9.jpg

#include <iostream>
#include <cstdio>
#include <cstring>
#define mod 1000000007
#define LL long long
using namespace std;

struct Obj
{
    LL m[3][3];
    Obj() {memset(m, 0, sizeof(m));}
};
LL n;

Obj mul(Obj a, Obj b)
{
    Obj c;
    for(LL i = 1; i <= 2; i++)
        for(LL j = 1; j <= 2; j++)
            for(LL k = 1; k <= 2; k++)
                c.m[i][j] += (a.m[i][k] % mod * b.m[k][j] % mod) % mod,
                c.m[i][j] %= mod;
    return c;
}

Obj power(Obj a, LL b)
{
    Obj d;  d.m[1][1] = d.m[2][2] = 1;
    Obj r = d, base = a;
    while(b)
    {
        if(b & 1) r = mul(r, base);
        base = mul(base, base);
        b >>= 1;
    }
    return r;
}

int main()
{
    cin >> n;
    if(n <= 2) {cout << 1; return 0;}
    Obj t1; t1.m[1][1] = t1.m[1][2] = t1.m[2][1] = 1; //系数矩阵 
    Obj ans = power(t1, n - 2);
    Obj t2; t2.m[1][1] = t2.m[2][1] = 1; //初始矩阵 
    Obj t3; //结果矩阵 
    for(LL i = 1; i <= 2; i++)
        for(LL j = 1; j <= 1; j++)
            for(LL k = 1; k <= 2; k++)
                t3.m[i][j] += (ans.m[i][k] % mod * t2.m[k][j] % mod) % mod,
                t3.m[i][j] %= mod;
    cout << t3.m[1][1];
    return 0;
}

转载于:https://www.cnblogs.com/BigYellowDog/p/11204437.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值