-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathM_Power_Matrix.cpp
More file actions
91 lines (65 loc) · 1.48 KB
/
Copy pathM_Power_Matrix.cpp
File metadata and controls
91 lines (65 loc) · 1.48 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// 행렬의 거듭제곱을 빠르게 표현하는 알고리즘
// 행렬의 거듭제곱을 빠르게 표현하는 알고리즘
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long ll;
vector<vector<ll>> multiple(vector<vector<ll>>& a, vector<vector<ll>>& b)
{
// equal sizeof
int len = a.size();
vector<vector<ll>> res(len, vector<ll>(len));
for(int i=0;i<len;i++)
{
for(int j=0;j<len;j++)
{
for(int k=0;k<len;k++)
{
res[i][j] += a[i][k]*b[k][j];
}
res[i][j]%=1000;
}
}
return res;
}
vector<vector<ll>> power_matrix(vector<vector<ll>>& a, ll m)
{
int len = a.size();
vector<vector<ll>> res(len, vector<ll>(len));
for(int i=0;i<len;i++)
res[i][i]=1;
while(m>0)
{
if(m%2==1)
{
res = multiple(res, a);
}
m/=2;
a = multiple(a, a);
}
return res;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n; ll m;
cin>>n>>m;
vector<vector<ll>> a(n, vector<ll>(n));
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
cin>>a[i][j];
}
auto res = power_matrix(a, m);
for(auto i : res)
{
for(auto j : i)
cout<<j<<" ";
cout<<'\n';
}
return 0;
}