-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMatrix Power.cpp
52 lines (45 loc) · 1.13 KB
/
Matrix Power.cpp
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
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
const int mod = 1e9+7;
vvi matrixUnit(int n) {
vvi res(n, vi(n));
for (int i = 0; i < n; i++)
res[i][i] = 1;
return res;
}
vvi matrixAdd(const vvi &a, const vvi &b) {
int n = a.size();
int m = a[0].size();
vvi res(n, vi(m));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
res[i][j] = (a[i][j] + b[i][j]) % mod;
return res;
}
vvi matrixMul(const vvi &a, const vvi &b) {
int n = a.size();
int m = a[0].size();
int k = b[0].size();
vvi res(n, vi(k));
for (int i = 0; i < n; i++)
for (int j = 0; j < k; j++)
for (int p = 0; p < m; p++)
res[i][j] = (res[i][j] + (long long) a[i][p] * b[p][j]) % mod;
return res;
}
vvi matrixPow(const vvi &a, int p) {
if (p == 0)
return matrixUnit(a.size());
if (p & 1)
return matrixMul(a, matrixPow(a, p - 1));
return matrixPow(matrixMul(a, a), p / 2);
}
int main() {
vvi a(2, vi(2));
a[0][0] = 1;
a[0][1] = 1;
a[1][0] = 1;
vvi b = matrixPow(a, 10);
}