矩阵快速幂 模板

由矩阵乘法结合律

(A×B)×C=A×(B×C)(A \times B) \times C = A \times (B \times C)

可以先计算转移矩阵BB的幂,再与初始矩阵AA相乘

A×BnA \times B^n

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

typedef long long int ll;

const ll m = 123456789; // MOD

ll k;
int N = 6; // matrix size
struct matrix
{
ll g[N][N];
matrix operator=(const matrix &b)
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
g[i][j] = b.g[i][j];
}
}
return *this;
}
}a,b;

matrix operator*(const matrix &a, const matrix &b)
{
matrix c;
memset(c.g, 0, sizeof(c.g));
for (ll i = 0; i < N; i++)
for (ll k = 0; k < N; k++)
{
if (a.g[i][k] == 0)
{
continue;
}
for (ll j = 0; j <N; j++)
c.g[i][j] = (c.g[i][j] + a.g[i][k]*b.g[k][j] %m) % m;
}
return c;
}

matrix pow(matrix a, ll b)
{
matrix ans;
memset(ans.g, 0, sizeof(ans.g));
for (int i = 0; i < N; i++)
{
ans.g[i][i] = 1;
}
while (b)
{
if (b & 1)
ans = ans * a;
a = a * a;
b >>= 1;
}
return ans;
}