UVA 10689 Yet another Number Sequence
题目链接:UVA 10689 Yet another Number Sequence
题目大意:
将斐波那契数列的\(f_0\)和\(f_1\)改为\(a\)和\(b\),求\(f_n\)的后\(m\)位。
题解:
很典型的一道矩阵快速幂的题目。
构造矩阵:
\[\left(\begin{matrix}
f_i \\
f_{i-1}
\end{matrix}\right)
=
\left(\begin{matrix}
1 & 1 \\
1 & 0
\end{matrix}\right)
\times
\left(\begin{matrix}
f_{i-1} \\
f_{i-2}
\end{matrix}\right)
\]
所以:
\[\left(\begin{matrix}
f_n \\
f_{n-1}
\end{matrix}\right)
=
\left(\begin{matrix}
1 & 1 \\
1 & 0
\end{matrix}\right)^{n-1}
\times
\left(\begin{matrix}
b \\
a
\end{matrix}\right)
\]
取后\(m\)位则直接在矩阵快速幂的过程中对\(10^m\)取余就行了。
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
#define ll long long
const int mod[] = {0, 10, 100, 1000, 10000};
struct Matrix { // 矩阵
int row, col;
ll num[2][2];
};
Matrix multiply(Matrix a, Matrix b, int mod) { // 矩阵乘法
Matrix temp;
temp.row = a.row, temp.col = b.col;
memset(temp.num, 0, sizeof(temp.num));
for (int i = 0; i < a.row; ++i)
for (int j = 0; j < b.col; ++j)
for (int k = 0; k < a.col; ++k)
temp.num[i][j] =
(temp.num[i][j] + a.num[i][k] * b.num[k][j]) % mod;
return temp;
}
Matrix MatrixFastPow(Matrix base, ll k, int mod) { // 矩阵快速幂
Matrix ans;
ans.row = ans.col = 2;
ans.num[0][0] = ans.num[1][1] = 1;
ans.num[0][1] = ans.num[1][0] = 0;
while (k) {
if (k & 1) ans = multiply(ans, base, mod);
base = multiply(base, base, mod);
k >>= 1;
}
return ans;
}
int main() {
ll a, b, n, m, t;
cin >> t;
Matrix base;
base.row = base.col = 2;
base.num[0][0] = base.num[0][1] = base.num[1][0] = 1;
base.num[1][1] = 0;
while (t--) {
cin >> a >> b >> n >> m;
Matrix ans = MatrixFastPow(base, n - 1, mod[m]);
cout << (ans.num[0][0] * b + ans.num[0][1] * a) % mod[m] << endl;
}
return 0;
}