哈尔滨理工大学软件学院ACM程序设计全国邀请赛 F Fibonacci Again (矩阵快速幂)

F Fibonacci Again Description

There are another kind of Fibonacci numbers: F(0) = 7, F(1) = 11, F(n) = (F(n-1) + F(n-2)) xor (n&1) (n>=2). 
 
 Input

consists of a sequence of lines, each containing an integer n. (0<=n < 1,000,000,000).
 
Output 

F(n) mod 1000000007.
 
 
Sample Input

2 3 4 5 


Sample Output

18 28 46 75

解题思路:解决本题的一个关键就是发现其表达式和原来的斐波那契数列的不同,通过打表分析观察,可以发现一个以6为周期的循环。


通过这些表达式就可以将这道问题转化成常见的矩阵快速幂问题了,因为后面存在常数项,所以需要构造一个7*7的矩阵。微笑








由此就可以套用矩阵快速幂的思路解决此题了~


AC代码:

#include <bits/stdc++.h>

using namespace std;
typedef long long LL;

const int mod = 1000000007;
const int MAXN = 7;

typedef struct
{
    LL mat[MAXN][MAXN];
} Matrix;
const LL MOD = 1e9+7;
///求得的矩阵
Matrix P;
///单位矩阵
Matrix I;
void init()
{
    for(int i = 0; i<MAXN; i++)
    {
        for(int j = 0; j<MAXN; j++)
        {
            if(i==j) I.mat[i][j] = 1;
            else I.mat[i][j] = 0;
        }
    }
}
///矩阵乘法
Matrix Mul_Matrix(Matrix a, Matrix b)
{
    Matrix c;
    for(int i=0; i<MAXN; i++)
    {
        for(int j=0; j<MAXN; j++)
        {
            c.mat[i][j] = 0;
            for(int k=0; k<MAXN; k++)
            {
                c.mat[i][j] += (a.mat[i][k] * b.mat[k][j]) % MOD;
                c.mat[i][j] %= MOD;
            }
        }
    }
    return c;
}
///矩阵的快速幂
Matrix quick_Mod_Matrix(LL m)
{
    Matrix ans = I, b = P;
    while(m)
    {
        if(m & 1)
            ans = Mul_Matrix(ans, b);
        m>>=1;
        b = Mul_Matrix(b, b);
    }
    return ans;
}

LL g[10] = {7,11,18,28,46,75,1};
int main()
{
    //freopen("test.txt","w",stdout);
    LL n;
    while(cin>>n)
    {
        P.mat[5][5] = 13; P.mat[5][4] = 8; P.mat[5][6] = 4;
        P.mat[4][5] = 8; P.mat[4][4] = 5; P.mat[4][6] = 2;
        P.mat[3][5] = 5; P.mat[3][4] = 3; P.mat[3][6] = 1;
        P.mat[2][5] = 3; P.mat[2][4] = 2; P.mat[2][6] = 1;
        P.mat[1][5] = 2; P.mat[1][4] = 1; P.mat[1][6] = 1;
        P.mat[0][5] = 1; P.mat[0][4] = 1;
        P.mat[6][6] = 1;
        init();
        Matrix temp = quick_Mod_Matrix(n/6);
        LL ans[10] = {0};
        for(int i = 0; i<MAXN; i++)
        {
            for(int j = 0; j<MAXN; j++)
            {
                ans[i] += temp.mat[i][j]*g[j];
                ans[i] %= MOD;
            }
        }
        cout << ans[n%6] << endl;
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值