TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
matrix_exponentiation.cpp
Go to the documentation of this file.
1
25#include <iostream>
26#include <vector>
27
28using std::cin;
29using std::cout;
30using std::vector;
31
33#define ll int64_t
34
36#define endl std::endl
37
39#define pb push_back
40#define MOD 1000000007
41
46
50vector<ll> fib_b, fib_c;
51
57vector<vector<ll>> multiply(const vector<vector<ll>> &A,
58 const vector<vector<ll>> &B) {
59 vector<vector<ll>> C(mat_size + 1, vector<ll>(mat_size + 1));
60 for (ll i = 1; i <= mat_size; i++) {
61 for (ll j = 1; j <= mat_size; j++) {
62 for (ll z = 1; z <= mat_size; z++) {
63 C[i][j] = (C[i][j] + (A[i][z] * B[z][j]) % MOD) % MOD;
64 }
65 }
66 }
67 return C;
68}
69
76vector<vector<ll>> power(const vector<vector<ll>> &A, ll p) {
77 if (p == 1)
78 return A;
79 if (p % 2 == 1) {
80 return multiply(A, power(A, p - 1));
81 } else {
82 vector<vector<ll>> X = power(A, p / 2);
83 return multiply(X, X);
84 }
85}
86
91ll ans(ll n) {
92 if (n == 0)
93 return 0;
94 if (n <= mat_size)
95 return fib_b[n - 1];
96 // F1
97 vector<ll> F1(mat_size + 1);
98 for (ll i = 1; i <= mat_size; i++) F1[i] = fib_b[i - 1];
99
100 // Transpose matrix
101 vector<vector<ll>> T(mat_size + 1, vector<ll>(mat_size + 1));
102 for (ll i = 1; i <= mat_size; i++) {
103 for (ll j = 1; j <= mat_size; j++) {
104 if (i < mat_size) {
105 if (j == i + 1)
106 T[i][j] = 1;
107 else
108 T[i][j] = 0;
109 continue;
110 }
111 T[i][j] = fib_c[mat_size - j];
112 }
113 }
114 // T^n-1
115 T = power(T, n - 1);
116
117 // T*F1
118 ll res = 0;
119 for (ll i = 1; i <= mat_size; i++) {
120 res = (res + (T[1][i] * F1[i]) % MOD) % MOD;
121 }
122 return res;
123}
124
126int main() {
127 cin.tie(0);
128 cout.tie(0);
129 ll t;
130 cin >> t;
131 ll i, j, x;
132 while (t--) {
133 cin >> mat_size;
134 for (i = 0; i < mat_size; i++) {
135 cin >> x;
136 fib_b.pb(x);
137 }
138 for (i = 0; i < mat_size; i++) {
139 cin >> x;
140 fib_c.pb(x);
141 }
142 cin >> x;
143 cout << ans(x) << endl;
144 fib_b.clear();
145 fib_c.clear();
146 }
147 return 0;
148}
vector< vector< ll > > multiply(const vector< vector< ll > > &A, const vector< vector< ll > > &B)
vector< ll > fib_b
#define endl
vector< vector< ll > > power(const vector< vector< ll > > &A, ll p)