地斗主
题目地址:
基本思路:
我们看到对于的数据
,所以很明显这题应该能推出公式,
因此,我们手推或者打表出前几项,然后我们用我们睿智的头脑,和锐利眼光去观察(
使用oeis),就能得到如下递推式:
.
然后我们每次使用矩阵快速幂就能得到答案了。
update :
直接用的方法并不可取,我们还是来推一推这个递推式:
我们先设长为的棋盘的方案数为
,
长为的棋盘的不可分离的棋盘的数量设为
,
我们画图可以发现,,
也就是说如果,
为奇数
否则
;
那么我们可以得到:
,
,
所以上下一减我们公式最终就能化简为:
根据这个线性递推式我们使用矩阵快速幂就能得到答案了。
参考代码:
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false); cin.tie(0)
#define int long long
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
#define INF 1e18
inline int read() {
int x = 0, neg = 1; char op = getchar();
while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
return neg * x;
}
inline void print(int x) {
if (x < 0) { putchar('-'); x = -x; }
if (x >= 10) print(x / 10);
putchar(x % 10 + '0');
}
int mod;
struct MAT {
int v[5][5];
int n, m;
MAT(int _n = 0, int _m = 0) {
n = _n;
m = _m;
}
void clear() {
memset(v, 0, sizeof(v));
}
};
MAT operator * (MAT a, MAT b) {
MAT ans(a.n, b.m);
ans.clear();
for (int i = 0; i < a.n; i++) {
for (int j = 0; j < b.m; j++) {
for (int k = 0; k < a.m; k++) {
ans.v[i][j] = (ans.v[i][j] + a.v[i][k] * b.v[k][j]) % mod;
}
}
}
return ans;
}
/*
f(n) = f(n-1) + 5*f(n-2) + f(n-3) - f(n-4).
*/
int n;
signed main() {
IO;
int t;
cin >> t;
while (t--) {
cin >> n >> mod;
int a_1 = 1, a_2 = 5, a_3 = 11, a_4 = 36;
if (n <= 4) {
if (n == 1) cout << a_1 << '\n';
else if (n == 2) cout << a_2 << '\n';
else if (n == 3) cout << a_3 << '\n';
else cout << a_4 << '\n';
continue;
}
MAT ans(4, 1), res(4, 4);
ans.clear(), res.clear();
ans.v[0][0] = a_4, ans.v[1][0] = a_3, ans.v[2][0] = a_2, ans.v[3][0] = a_1;
res.v[0][0] = 1, res.v[0][1] = 5, res.v[0][2] = 1, res.v[0][3] = -1;
res.v[1][0] = 1, res.v[2][1] = 1, res.v[3][2] = 1;
n -= 4;
while (n > 0) {
if (n & 1) ans = res * ans;
res = res * res;
n >>= 1;
}
cout << (ans.v[0][0] + mod) % mod << '\n';
}
return 0;
}

京公网安备 11010502036488号