-
Notifications
You must be signed in to change notification settings - Fork 0
/
matrix multiplication example.cpp
65 lines (56 loc) · 1.76 KB
/
matrix multiplication example.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
53
54
55
56
57
58
59
60
61
62
63
64
65
// UVa10870 Recurrences
// Rujia Liu
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
const int maxn = 20;
typedef long long Matrix[maxn][maxn];// declare Matrix as the alias of an 2d array with maxn * maxn as its dimension.
typedef long long Vector[maxn];
int sz, mod;
void matrix_mul(Matrix A, Matrix B, Matrix res) {// when array is passed into the function, only the pointer is passed in.
Matrix C;
memset(C, 0, sizeof(C));//So memset and memcpy is revising the original array.
for(int i = 0; i < sz; i++)
for(int j = 0; j < sz; j++)
for(int k = 0; k < sz; k++) C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % mod;
memcpy(res, C, sizeof(C));
}
void matrix_pow(Matrix A, int n, Matrix res) {
Matrix a, r;
memcpy(a, A, sizeof(a));
memset(r, 0, sizeof(r));
for(int i = 0; i < sz; i++) r[i][i] = 1;//initialize r matrix to identity matrix
while(n) {
if(n&1) matrix_mul(r, a, r);//if n is odd, r *= a;
n >>= 1;//r /= 2
matrix_mul(a, a, a);//a = a^2
}
memcpy(res, r, sizeof(r));
}
void transform(Vector d, Matrix A, Vector res) {
Vector r;
memset(r, 0, sizeof(r));
for(int i = 0; i < sz; i++)
for(int j = 0; j < sz; j++)
r[j] = (r[j] + d[i] * A[i][j]) % mod;
memcpy(res, r, sizeof(r));
}
int main() {
int d, n, m;
while(cin >> d >> n >> m && d) {
Matrix A;
Vector a, f;
for(int i = 0; i < d; i++) { cin >> a[i]; a[i] %= m; }
for(int i = d-1; i >= 0; i--) { cin >> f[i]; f[i] %= m; }
memset(A, 0, sizeof(A));
for(int i = 0; i < d; i++) A[i][0] = a[i];
for(int i = 1; i < d; i++) A[i-1][i] = 1;
sz = d;
mod = m;
matrix_pow(A, n-d, A);
transform(f, A, f);
cout << f[0] << endl;
}
return 0;
}