前言
思路
思路来自 : 彩色铅笔 ,
写的很好,我就不做什么补充了
Mycode
#include <iostream>
#include <cstring>
using namespace std;
typedef long long LL;
const int N = 4;
int n, m;
void mul(int a[][N], int b[][N], int c[][N]) {
static int t[N][N];
memset(t, 0, sizeof t);
for (int i = 0; i < N; ++ i) {
for (int j = 0; j < N; ++ j) {
for (int k = 0; k < N; ++ k) {
t[i][j] = (t[i][j] + (LL)a[i][k] * b[k][j] % m) % m;
}
}
}
memcpy(c, t, sizeof t);
}
int main() {
int a[N][N] = {1, 0, 0, 0};
int b[N][N] = {
{1, 1, 1, 0},
{1, 0, 0, 0},
{0, 0, 1, 1},
{0, 0, 0, 1}
};
scanf("%d%d", &n, &m);
for (int i = n; i; i >>= 1) {
if (i & 1) mul(a, b, a);
mul(b, b, b);
}
LL t = 1ll * n * a[0][2] - a[0][3];
t = (t % m + m) % m;
printf("%lld\n", t);
return 0;
}