题目:
不知道为什么今天下午做矩阵快速幂上头。
由题意:
我们只需要找到 与 的线性递推关系即可。
我们可以得到如下三个线性方程
于是
最后我们就可以使用矩阵快速幂求解了。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
struct matrix {
ll a[4][4];
matrix() {
memset(a, 0, sizeof(a));
}
matrix operator * (const matrix& b) {
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] % mod + a[i][k] % mod * b.a[k][j] % mod + mod) % mod;
}
}
}
return res;
}
};
ll power(ll n)
{
matrix ans, base;
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
ans. a[i][j] = base.a[i][j] = 0;
}
}
ans.a[1][1] = ans.a[1][2] = ans.a[1][3] = 1;
base.a[1][1] = base.a[1][2] = 1;
base.a[2][3] = 1;
base.a[3][1] = 1;
while(n) {
if(n & 1) ans = ans * base;
base = base * base;
n >>= 1;
}
return ans.a[1][1];
}
int main()
{
int t;
ll n;
scanf("%d", &t);
while(t--) {
scanf("%lld", &n);
if(n == 1 || n == 2 || n == 3) printf("1\n");
else printf("%lld\n", power(n-3));
}
}