Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
topic:
I do not know why this afternoon matrix fast power top.
Meaning of the questions:
We just need to find the linear recurrence relation to the.
We can obtain the following three linear equations
then
Finally, we can use the power of the matrix quickly solved.
#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));
}
}