Matrix Multiplication (& Quick Power)
求图中那个有根号,有幂,有下取整的变态公式的值。
Type
Matrix Multiplication
Quick Power
Analysis
这题首先要注意不能将一个实数取模,即使你把它拆成整数部分和小数部分。
要用数学方法来解这题,我是解释不来的,所以这里引用一下牛人的推导:
推倒~之后,我们就可以利用矩阵乘法去求Xn,然后计算出梦寐以求的 ans 了。
Solution
// HDOJ 2256
// Problem of Precision
// by A Code Rabbit
#include <cstdio>
#include <cstring>
const int MAXO = 4;
const int MOD = 1024;
template <typename T>
struct Matrix {
T e[MAXO][MAXO];
int o;
Matrix(int x) { memset(e, 0, sizeof(e)); o = x; }
Matrix operator*(const Matrix& one) {
Matrix res(o);
for (int i = 0; i < o; i++) {
for (int j = 0; j < o; j++) {
for (int k = 0; k < o; k++)
res.e[i][j] += e[i][k] * one.e[k][j];
res.e[i][j] %= MOD;
}
}
return res;
}
Matrix operator*=(const Matrix& one) { return *this = *this * one; }
};
template <typename T>
T QuickPower(T radix, int exp) {
T res = radix;
exp--;
while (exp) {
if (exp & 1) res *= radix;
exp >>= 1;
radix *= radix;
}
return res;
}
int n;
Matrix<int> radix(2);
int main() {
int tot_case;
scanf("%d", &tot_case);
while (tot_case--) {
// Input.
scanf("%d", &n);
// Solve.
radix.e[0][0] = 5;
radix.e[0][1] = 2;
radix.e[1][0] = 12;
radix.e[1][1] = 5;
Matrix<int> ans = QuickPower(radix, n - 1);
// Compute and output.
int x_n = (5 * ans.e[0][0] + 2 * ans.e[1][0]) % MOD;
printf("%d\n", (x_n * 2 - 1) % MOD);
}
return 0;
}