51NOD 1358 浮波那契 【矩阵快速幂】

1358 浮波那契
基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题

TengBieBie已经学习了很多关于斐波那切数列的性质,所以他感到一些些厌烦。现在他遇到了一个新的数列,这个数列叫做Float-Bonacci。这里有一个关于Float-Bonacci的定义。


对于一个具体的n,TengBieBie想要快速计算FB(n).

但是TengBieBie对FB的了解非常少,所以他向你求助。

你的任务是计算FB(n).FB(n)可能非常大,请输出FB(n)%1,000,000,007 (1e9+7)即可。
Input

输入共一行,在一行中给出一个整数n (1<=n<=1,000,000,000)。

Output

对于每一个n,在一行中输出FB(n)%1,000,000,007 (1e9+7)。

Input示例

5

Output示例

2

System Message (题目提供者)

比较裸的矩阵快速幂问题 (这样也4级…)

n=n10

F(n)=F(n10)+F(n34)

#include<stdio.h>
#include<bits/stdc++.h>
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define MEM(a,x) memset(a,x,sizeof(a))
#define lowbit(x) ((x)&-(x))

using namespace std;

const int inf = 1e9+7;
const int N = 1e4+7;

struct Matrix {
    const static int sz = 34;
    ll mat[sz][sz];

    Matrix(bool E = false){
        MEM(mat,0);
        if(E){
            for(int i=0;i<sz;++i){
                mat[i][i]=1;
            }
        }
    }

    ll* operator[](const int idx){
        return mat[idx];
    }

    const ll* operator [](const int idx)const{
        return mat[idx];
    }

    Matrix operator*(const Matrix&other){
        Matrix ans;
        for(int i=0;i<sz;++i){
            for(int j=0;j<sz;++j){
                ans[i][j]=0;
                for(int k=0;k<sz;++k){
                    ans[i][j]+=mat[i][k]*other[k][j];
                    ans[i][j]%=inf;
                }
            }
        }
        return ans;
    }

    Matrix operator^(ll n){
        Matrix ans(true);
        Matrix tmp = *this;
        while(n>0){
            if(n&1){
                ans = ans*tmp;
            }
            tmp = tmp*tmp;
            n>>=1;
        }
        return ans;
    }

};

Matrix m;

void init(){
    m[0][9]=m[0][33]=1;
    for(int i=1;i<34;++i){
        m[i][i-1]=1;
    }
}

ll slove(ll n){
    if(n<41){
        return 1;
    }
    Matrix t = m^(n-40);
    ll ans = 0;
    for(int i = 0; i < 34; ++i){
        ans += t[0][i];
        ans %= inf;
    }
    return ans;
}

int main(){
    //freopen("/home/lu/code/r.txt","r",stdin);
    //freopen("/home/lu/code/w.txt","w",stdout);
    ll n;
    init();
    while(~scanf("%lld",&n)){
        n*=10;
        printf("%lld\n",slove(n));
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值