-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrix.java
More file actions
65 lines (59 loc) · 1.52 KB
/
Matrix.java
File metadata and controls
65 lines (59 loc) · 1.52 KB
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
58
59
60
61
62
63
64
65
public class Matrix {
static final MOD = (int)1e9 + 7;
static int add(int x, int y) {
x += y;
if (x >= MOD) {
x -= MOD;
}
return x;
}
static int sub(int x, int y) {
x -= y;
if (x < 0) {
x += MOD;
}
return x;
}
static int mul(int x, int y) {
long result = (long) x * y % MOD;
return (int) result;
}
static int[][] Ident(int n) {
int[][] result = new int[n][n];
for (int i = 0; i < n; i++) {
result[i][i] = 1;
}
return result;
}
static int[][] Multy(int[][] a, int[][] b) {
int na = a.length, ma = a[0].length;
int nb = b.length, mb = b[0].length;
assert ma == nb;
int[][] c = new int[na][mb];
for (int i = 0; i < na; i++) {
for (int j = 0; j < mb; j++) {
for (int k = 0; k < nb; k++) {
c[i][j] = add(c[i][j], mul(a[i][k], b[k][j]));
}
}
}
return c;
}
static int[][] Power(int[][] a, long k) {
int n = a.length;
int[][] b = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
b[i][j] = a[i][j];
}
}
int[][] result = Ident(n);
for ( ; k > 0; k >>= 1) {
if (k % 2 == 1) {
result = Multy(result, b);
}
b = Multy(b, b);
}
return result;
}
}