洛谷P1939
题目链接
题目描述
已知一个数列 aa,它满足:
求 a数列的第 n 项对 109+7 取余的值。
思路:
数据范围很大,直接递推肯定TLE,由递推想到矩阵快速幂,矩阵快速幂运算思想与普通快速幂运算一致,只不过借助了矩阵运算。解题的关键在于得到目标矩阵和构造初始矩阵。一定要注意矩阵的左乘和和右乘!
code:
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#define debug(x) cout << #x << ":" << x << endl;
#define fi first
#define se second
using namespace std;
typedef long long ll;
const double eps = 1e-10;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const double pi = acos(-1.0);
const int mod = 1e9 + 7;
const int maxn = 2e5 + 10;
struct mat{
ll m[3][3];
} ans, tran;
void init()
{
memset(ans.m, 0, sizeof ans.m);
memset(tran.m, 0, sizeof tran.m);
ans.m[0][0] = ans.m[1][0] = ans.m[2][0] = 1;//目标矩阵
tran.m[0][0] = tran.m[0][2] = tran.m[1][0] = tran.m[2][1] = 1;//初始矩阵
}
mat mul(mat a,mat b)
{//矩阵运算
mat ret;
memset(ret.m, 0, sizeof ret.m);
for (int i = 0; i < 3;i++){
for (int j = 0; j < 3;j++){
for (int k = 0; k < 3;k++){
ret.m[i][j] = (ret.m[i][j] + a.m[i][k] * b.m[k][j]) % mod;
}
}
}
return ret;
}
void qpow(int a)
{//快速幂运算
while(a){
if(a&1)
ans = mul(tran, ans);//表示矩阵tran.m*ans.m,不要写反了!
a >>= 1;
tran = mul(tran, tran);
}
}
int main()
{
int n, t;
scanf("%d", &t);
while(t--){
scanf("%d", &n);
if(n<=3)
puts("1");
else {
init();
qpow(n-3);
int a = ans.m[0][0];
printf("%lld\n", a);
}
}
return 0;
}