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

来源:互联网 发布:java linkedlist 删除 编辑:程序博客网 时间:2024/05/02 00:44

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