武大oj 校赛 Problem 1540 - D - Fibonacci

Description

Calculate the sum of the cubes of the first n items in Fibonacci sequence in which the first two are both 1.
Input
The input consists of one or more test cases.

First line of each test case consists only one integer n. (1<=n<=10^9)

Input is terminated by a value of zero (0) for n.
Output
For each test case, output the answer mod 1000000007.
Sample Input
1
2
3
Sample Output
1
2
10
/*AC*/
#include <stdio.h>
#include <string.h>
#include <iostream>

using namespace std;
typedef long long LL;
typedef struct matrix {
    LL a[5][5];
} matrix;

const int MOD = 1000000007;
matrix E, M;

void InitE() {
    for (int i = 0; i < 5; i++)
        for (int j = 0; j < 5; j++)
            E.a[i][j] = (i == j);
}

void InitM() {
    M.a[0][0] = 1; M.a[0][1] = 3; M.a[0][2] = 3; M.a[0][3] = 1; M.a[0][4] = 0;
    M.a[1][0] = 1; M.a[1][1] = 2; M.a[1][2] = 1; M.a[1][3] = 0; M.a[1][4] = 0;
    M.a[2][0] = 1; M.a[2][1] = 1; M.a[2][2] = 0; M.a[2][3] = 0; M.a[2][4] = 0;
    M.a[3][0] = 1; M.a[3][1] = 0; M.a[3][2] = 0; M.a[3][3] = 0; M.a[3][4] = 0;
    M.a[4][0] = 1; M.a[4][1] = 0; M.a[4][2] = 0; M.a[4][3] = 0; M.a[4][4] = 1;
}

matrix mul(matrix A, matrix B) {
    matrix C;
    for (int i = 0; i < 5; i++)
        for (int k = 0; k < 5; k++) {
            C.a[i][k] = 0;
            for (int j = 0; j < 5; j++)
                C.a[i][k] = (C.a[i][k] + (A.a[i][j] * B.a[j][k]) % MOD) % MOD;
    }
    return C;
}

matrix pow(matrix A, LL n) {
    matrix C = E;
    while (n > 0) {
        if (n & 1)
            C = mul(C, A);
        A = mul(A, A);
        n >>= 1;
    }
    return C;
}

int main() {
    LL n;
    InitE();
    InitM();
    while (cin >> n) {
        if (n == 0)
            break;
        matrix ans;
        for (int i = 0; i < 5; i++)
            for (int j = 0; j < 5; j++)
                ans.a[i][j] = 0;
        for (int i = 0; i < 5; i++)
            ans.a[i][0] = 1;
        matrix r = pow(M, n - 1);
        ans = mul(r, ans);
        cout << ans.a[4][0] << endl;
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值