欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

2018年湘潭大学程序设计竞赛G又见斐波那契(矩阵快速幂)

程序员文章站 2023-11-17 23:24:16
题意 题目链接 Sol 直接矩阵快速幂 推出来的矩阵应该长这样 \begin{equation*}\begin{bmatrix}1&1&1&1&1&1\\1 & 0&0&0&0&0\\0 & 0&1&3&3&1\\0 & 0&0&1&2&1\\0 & 0&0&0&1&1\\0 & 0&0&0&0&1 ......

题意

题目链接

2018年湘潭大学程序设计竞赛G又见斐波那契(矩阵快速幂)

sol

直接矩阵快速幂

推出来的矩阵应该长这样

\begin{equation*}
\begin{bmatrix}
1&1&1&1&1&1\\
1 & 0&0&0&0&0\\
0 & 0&1&3&3&1\\
0 & 0&0&1&2&1\\
0 & 0&0&0&1&1\\
0 & 0&0&0&0&1\\
\end{bmatrix}^{i - 1}*
\begin{bmatrix}
f_{1}\\
f_0\\
1\\
1\\
1\\
1
\end{bmatrix}=
\begin{bmatrix}
1&1&1&1&1&1\\
1 & 0&0&0&0&0\\
0 & 0&1&3&3&1\\
0 & 0&0&1&2&1\\
0 & 0&0&0&1&1\\
0 & 0&0&0&0&1\\
\end{bmatrix}*
\begin{bmatrix}
f_{i - 1}\\
f_{i - 2}\\
i^3\\
i^2\\
i\\
1
\end{bmatrix}=
\begin{bmatrix}
f_{i}\\
f_{i - 1}\\
(i + 1)^3\\
(i + 1)^2\\
i + 1\\
1
\end{bmatrix}
\end{equation*}

#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
#define pair pair<int, int> 
#define mp(x, y) make_pair(x, y)
#define fi first
#define se second
#define ll long long
//#define int long long  
using namespace std;
const int mod = 1e9 + 7;
inline ll read() {
    char c = getchar(); ll x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int t;
ll n;
struct matrix {
    ll a[10][10], n;
    matrix() {
        n = 6;
        memset(a, 0, sizeof(a));
    }
    matrix operator * (const matrix &rhs) const {
        matrix ans;
        for(int k = 1; k <= n; k++) 
            for(int i = 1; i <= n; i++)
                for(int j = 1; j <= n; j++) 
                    (ans.a[i][j] += (1ll * a[i][k] * rhs.a[k][j]) % mod) %= mod;
        return ans;
    }
};
matrix fp(matrix a, ll p) {
    matrix base;
  //  printf("%d", base.a[0][1]);
    for(int i = 1; i <= 6; i++) base.a[i][i] = 1;
    while(p) {
        if(p & 1) base = base * a;
        a = a * a; p >>= 1;
    }
    return base;
}
const ll gg[10][10] = {
       {0, 0, 0, 0, 0, 0, 0},
       {0, 1, 1, 1, 1, 1, 1},
       {0, 1, 0, 0, 0, 0, 0},
       {0, 0, 0, 1, 3, 3, 1},
       {0, 0, 0, 0, 1, 2, 1},
       {0, 0, 0, 0, 0, 1, 1},
       {0, 0, 0, 0, 0, 0, 1}
};
int main() {
    t = read();
    while(t--) {
        n = read();
        if(n == 1) {puts("1"); continue;}
        if(n == 2) {puts("16"); continue;}
        matrix m;
        memcpy(m.a, gg, sizeof(m.a));
        matrix ans = fp(m, n - 2);
        ll out = 0;
        (out += ans.a[1][1] * 16) %= mod;
        (out += ans.a[1][2] * 1) %= mod;
        (out += ans.a[1][3] * 27) %= mod;
        (out += ans.a[1][4] * 9) %= mod;
        (out += ans.a[1][5] * 3) %= mod;
        (out += ans.a[1][6]) %= mod;
        printf("%lld\n", out % mod);
    }
    return 0;
}
/*
5
4
1
2
3
100
*/