Skip to content

Commit b1ee5ca

Browse files
committed
Matrix Exponentiation, Linear Recurrence
1 parent 8606c9b commit b1ee5ca

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

SUMSUMS-d.cpp

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
typedef long long int ll;
5+
typedef vector<vector<ll> > vii;
6+
typedef vector<ll> vi;
7+
8+
const int m = 98765431;
9+
int k;
10+
vi b;
11+
12+
//matrix mul
13+
vii mul(const vii& A, const vii& B) {
14+
vii C(k, vi(k, 0));
15+
16+
for (int r = 0; r < k; ++r) {
17+
for (int c = 0; c < k; ++c) {
18+
for (int x = 0; x < k; ++x) {
19+
C[r][c] += (A[r][x] * B[x][c]) % m;
20+
C[r][c] %= m;
21+
}
22+
}
23+
}
24+
return C;
25+
}
26+
27+
//matrix exponentiation
28+
vii pow(vii& A, int n) {
29+
if (n <= 1) return A;
30+
31+
//if odd
32+
if (n & 1) return mul(A, pow(A, n - 1));
33+
34+
vii ans = pow(A, n / 2);
35+
return mul(ans, ans);
36+
}
37+
38+
39+
vi sol(int n){
40+
//TLE since k could be of the range 50000
41+
42+
//creating transformation mat
43+
vii t(k, vi(k, 0));
44+
45+
if (n < 1) return b;
46+
47+
for(int i = 0; i < k; ++i){
48+
for(int j = 0; j < k; ++j){
49+
if (i != j) t[i][j] = 1;
50+
}
51+
}
52+
53+
vii tn = pow(t, n);
54+
vi ans;
55+
ll x = 0;
56+
57+
for(int r = 0; r < k; ++r){
58+
for(int c = 0; c < k; ++c){
59+
x += (tn[r][c] * b[c]) % m;
60+
x %= m;
61+
}
62+
ans.push_back(x);
63+
x = 0;
64+
}
65+
return ans;
66+
}
67+
68+
69+
int main(){
70+
cin >> k;
71+
int n; cin >> n;
72+
b.resize(k);
73+
74+
for(int i = 0; i < k; ++i){
75+
cin >> b[i];
76+
}
77+
78+
vi ans = sol(n);
79+
for(int i = 0; i < k; ++i){
80+
cout << ans[i] << "\n";
81+
}
82+
}

0 commit comments

Comments
 (0)