洛谷题单指南-基础线性代数-P1939 矩阵加速(数列)
原题链接:https://www.luogu.com.cn/problem/P1939
题意解读:求数列第n项。
解题思路:矩阵快速幂加速递推。

100分代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MOD = 1e9 + 7;
struct Matrix
{
LL a[5][5];
Matrix()
{
memset(a, 0, sizeof(a));
}
Matrix operator * (const Matrix &to) const
{
Matrix res;
for(int i = 1; i <= 3; i++)
for(int j = 1; j <= 3; j++)
for(int k = 1; k <= 3; k++)
res.a[i][j] = (res.a[i][j] + a[i][k] * to.a[k][j]) % MOD;
return res;
}
} b3, A, ans;
LL t, n;
Matrix ksm(Matrix &a, LL b)
{
Matrix res;
res.a[1][1] = res.a[2][2] = res.a[3][3] = 1;
while(b)
{
if(b & 1) res = res * a;
b >>= 1;
a = a * a;
}
return res;
}
int main()
{
cin >> t;
while(t--)
{
cin >> n;
if(n <= 3)
{
cout << 1 << endl;
continue;
}
b3.a[1][1] = 1, b3.a[1][2] = 1, b3.a[1][3] = 1;
A.a[1][1] = 1, A.a[1][2] = 1, A.a[1][3] = 0,
A.a[2][1] = 0, A.a[2][2] = 0, A.a[2][3] = 1,
A.a[3][1] = 1, A.a[3][2] = 0, A.a[3][3] = 0;
ans = b3 * ksm(A, n - 3);
cout << ans.a[1][1] << endl;
}
return 0;
}
浙公网安备 33010602011771号