-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmatrix expo.cpp
More file actions
62 lines (55 loc) · 1.59 KB
/
matrix expo.cpp
File metadata and controls
62 lines (55 loc) · 1.59 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
// If we want to find the nth fibonacci num :
// Let M be (0 1, 1 1) matrix. It is M[2][2];
// then find M^n using mat expo.
// then multiply this matrix with (1, 1);
// this will give a matrix ans[1][2] which will be nth and n+1th term of fibonacci series.
// Be careful the sizes of matrix is not equal for the last multiplicaion :)
#include <bits/stdc++.h>
#define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL)
#define ll long long int
#define ld long double
using namespace std;
const int N = 1e5 + 5;
const int MOD = 42373;
int n;
vector<vector<long long int> > multiply(vector<vector<long long int> >a, vector<vector<long long int> > b){
vector<vector<long long> > ans(n, vector<long long int>(n, 0));
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
for(int tt = 0; tt < n; ++tt)
ans[i][j] = (ans[i][j] + (a[i][tt]*b[tt][j])) % MOD;
}
}
return ans;
}
vector<vector<long long int> > matrix_exponentiation(vector<vector<long long int> >a, int k){
vector<vector<long long int> > res(n, vector<long long int> (n, 0));
for(int i = 0; i < n; ++i)
res[i][i] = 1;
while(k > 0){
if(k % 2)
res = multiply(res, a);
a = multiply(a, a);
k /= 2;
}
return res;
}
void solve(){
cin >> n;
vector<vector<long long int> > a(n, vector<long long int> (n, 0));
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
cin >> a[i][j];
int str, tar, k;
cin >> str >> tar >> k;
vector<vector<long long int> > ans = matrix_exponentiation(a, k);
cout << ans[str - 1][tar - 1] % MOD << '\n';
}
int main(){
fast;
int t = 1;
// cin >> t;
while(t--)
solve();
return 0;
}