P5136 sequence 题解
题目链接:
\textbf{Update}
-
2022.10.24 被 @lingfunny Hack 了。
-
2023.3.1 修改并重写题解 & 代码。
\textbf{Description}
已知
\textbf{Solution}
显然这是一个斐波那契数列。
考虑其共轭:设
由共轭的性质,
那么一个思路是构造数列
也就是
我们需要通过
手推一下得到
- 注意取模 & 溢出问题;
- 特判
n=0 和n=1 的情况; - 注意
F_1=1,F_2=3 。
\textbf{AC Code}
#include <bits/stdc++.h>
#define int long long
const int p = 998244353;
int T, n;
struct Matrix {
int a[2][2];
Matrix() {memset(a, 0, sizeof(a));}
Matrix operator * (const Matrix &mat) {
Matrix res;
for(int i = 0; i < 2; i++) {
for(int k = 0; k < 2; k++) {
for(int j = 0; j < 2; j++) {
res.a[i][j] += a[i][k] * mat.a[k][j];
res.a[i][j] %= p;
}
}
} return res;
}
}ans, base;
inline void init() {
base.a[0][0] = 1, base.a[0][1] = 1;
base.a[1][0] = 1, base.a[1][1] = 0;
ans.a[0][0] = 3, ans.a[0][1] = 1;
ans.a[1][0] = 0, ans.a[1][1] = 0;
}
inline int solve(int b) {
init();
int f = (b -= 2) & 1;
while(b) {
if(b & 1) ans = ans * base;
base = base * base, b >>= 1;
} return (ans.a[0][0] + f) % p;
// Hack:注意先加再取模
}
signed main() {
std::cin >> T;
while(T--) {
std::cin >> n;
if(n == 0) {puts("1"); continue;}
if(n == 1) {puts("2"); continue;}
std::cout << solve(n) << std::endl;
}
return 0;
}