題目 "P1349 廣義斐波那契數列" 解析 把普通的矩陣乘法求斐波那契數列改一改,隨便一推就出來了 $$\begin{bmatrix}f_2\\f_1 \end{bmatrix}\begin{bmatrix} p&q\\ 1&0\\ \end{bmatrix}^{n 2}=\begin{bmatr ...
題目
解析
把普通的矩陣乘法求斐波那契數列改一改,隨便一推就出來了
\[\begin{bmatrix}f_2\\f_1
\end{bmatrix}\begin{bmatrix}
p&q\\
1&0\\
\end{bmatrix}^{n-2}=\begin{bmatrix}f_n\\f_{n-1}
\end{bmatrix}\]
水題
代碼
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 100;
int n, m, a1, a2, p, q;
struct matrix {
int a[N][N];
matrix() {
memset(a, 0, sizeof a);
}
void InitMatrix() {
a[1][1] = p, a[1][2] = q;
a[2][1] = 1;
}
matrix operator * (const matrix &oth) const {
matrix ans;
for (int k = 1; k <= 2; ++k)
for (int i = 1; i <= 2; ++i)
for (int j = 1; j <= 2; ++j)
ans.a[i][j] = (ans.a[i][j] + (a[i][k] * oth.a[k][j]) % m) % m;
return ans;
}
} init;
matrix qpow(matrix a, int b) {
matrix ans = init;
while (b) {
if (b & 1) ans = ans * a;
b >>= 1, a = a * a;
}
return ans;
}
template<class T>inline void read(T &x) {
x = 0; int f = 0; char ch = getchar();
for ( ; !isdigit(ch); ch = getchar()) f |= (ch == '-');
for ( ; isdigit(ch); ch = getchar()) x = x * 10 + ch - '0';
x = f ? -x : x;
return;
}
signed main() {
read(p), read(q), read(a1), read(a2), read(n), read(m);
if (n <= 2) {
printf("%lld", n == 1 ? a1 : a2);
return 0;
}
init.InitMatrix();
init = qpow(init, n - 3);
printf("%lld\n", (a2 * init.a[1][1] + a1 * init.a[1][2]) % m);
return 0;
}