-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrixExpo.cpp
More file actions
60 lines (49 loc) · 1.24 KB
/
MatrixExpo.cpp
File metadata and controls
60 lines (49 loc) · 1.24 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
/*
Matrix Expo
-----------
Let the matrix has R rows and C columns.
1. create matrix machine by: matExpo machine;
2. initialize with R,C: machine.init(R,C);
3. input A[R][C] machine.take(i,j,val);
4. calculate (A[][])^p machine.expo(p);
or, machine.loop(p);
Space complexity: O(R*R);
Time Complexity: O(R*R*R*lg(p));
*/
const LL mod = 1e9+7;
const LL inf = 2e18;
const LL matSize = 110;
struct matExpo{
LL mat[3][matSize][matSize];
LL a,res,temp;
LL r, c;
void init(LL R, LL C){
r = R, c = C;
a = 0 , res = 1 , temp = 2;
FOR(i,1,R)FOR(j,1,C){
mat[a][i][j] = inf;
mat[res][i][j] = inf;
}
};
void take(LL i, LL j, LL val){ mat[a][i][j] = mat[res][i][j] = val;}
void multiply( LL x, LL y , LL z ){
FOR(i,1,r)FOR(j,1,c){
mat[temp][i][j] = inf;
FOR(k,1,r){
if( max( mat[x][i][k],mat[y][k][j])<inf )
mat[temp][i][j] = min( mat[temp][i][j] , mat[x][i][k] + mat[y][k][j] );
}
}
FOR(i,1,r)FOR(j,1,c) mat[z][i][j] = mat[temp][i][j];
}
void expo(LL p){
while(p){
if(p&(1LL)) multiply(a,res,res);
p = p/2;
multiply(a,a,a);
}
}
void loop( LL p ){
FOR(i,1,p-1) multiply(a,res,res);
}
};