矩阵快速幂
矩阵快速幂就是快速幂的矩阵用法
ll Fast_Power(ll FP_a , ll FP_n , ll FP_p) {
///快速幂计算 a^n mod p
ll ret = 1 , A = FP_a;
while(FP_n) {
if (FP_n & 1)
ret = ( ret * A ) % FP_p;
A = ( A * A ) % FP_p;
FP_n >>= 1;
}
return ret;
}
得到递推公式后推出转移矩阵然后就套模版啦
#include <iostream>
#include <cstdio>
#define mod 1000000009
#define ll long long
using namespace std;
struct matrix {
ll mat[2][2];
};
matrix unit_matrix = {1, 0, 0, 1}; //单位矩阵
matrix mul(matrix a, matrix b) {
matrix res;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++) {
res.mat[i][j] = 0;
for (int k = 0; k < 2; k++) {
res.mat[i][j] = res.mat[i][j] + a.mat[i][k] * b.mat[k][j];
res.mat[i][j] = res.mat[i][j] % mod;
}
}
return res;
}
matrix pow_matrix(matrix a, ll n) {
matrix res = unit_matrix;
while (n != 0) {
if (n & 1)
res = mul(res, a);
a = mul(a, a);
n >>= 1;
}
return res;
}
int main() {
ll n;
while (~scanf("%lld",&n)) {
if (n <= 2) {
cout << "1" << endl;
continue;
}
matrix tmp = {0, 1, 1, 1}, ans, x = {1, 1, 0, 0};
ans = pow_matrix(tmp, n - 2);
ans = mul(x, ans);
cout << " ";
cout << ans.mat[0][1] << endl;
}
return 0;
}
以下是加强版嘻嘻嘻
#include <iostream>
#include <cstdio>
#define mod 1000000009
#define ll long long
using namespace std;
struct matrix {
ll mat[2][2];
};
matrix unit_matrix = {1, 0, 0, 1}; //单位矩阵
matrix mul(matrix a, matrix b, int x, int y, int z) { //xy a的行列 yz b的行列
matrix res;
for (int i = 0; i < x; i++)
for (int j = 0; j < z; j++) {
res.mat[i][j] = 0;
for (int k = 0; k < y; k++) {
res.mat[i][j] = res.mat[i][j] + a.mat[i][k] * b.mat[k][j];
res.mat[i][j] = res.mat[i][j] % mod;
}
}
return res;
}
matrix pow_matrix(matrix a, ll n, int x) {
matrix res = unit_matrix;
while (n != 0) {
if (n & 1)
res = mul(res, a, x, x, x);
a = mul(a, a, x, x, x);
n >>= 1;
}
return res;
}
int main() {
ll n;
while (~scanf("%lld", &n)) {
if (n <= 2) {
cout << "1" << endl;
continue;
}
matrix tmp = {0, 1, 1, 1}, ans, x = {1, 1};
ans = pow_matrix(tmp, n - 2, 2);
ans = mul(x, ans, 1, 2, 2);
cout << ans.mat[0][1] << endl;
}
return 0;
}