快速幂
例题:P1226 【模板】快速幂||取余运算#include<bits/stdc++.h> using namespace std; #define ll long long int a, b, p; int main() { cin >> a >> b >> p; int aa = a, bb = b; ll ans = 1; while (b) { if (b % 2 == 1) { ans = (ll)ans * a % p; } b /= 2; a = (ll) a * a % p; } printf("%d^%d mod %d=%ld\n", aa, bb, p, ans); return 0; }
矩阵快速幂
1.矩阵乘法
for(i = 1; i <= r; i ++) { for(j = 1; j <= c; j ++) { mul[i][j] = 0; for(k = 1; k <= c; k ++) { mul[i][j] += a[i][k] * b[k][j]; } } }
2.重载运算符
matrix operator *(const matrix &x, const matrix &y) { matrix z; for(int i = 1; i <= n; i ++) { for(int j = 1; j <= n; j ++) { for(int k = 1; k <= n; k ++) { z.a[i][j] = (z.a[i][j] + x.a[i][k] * y.a[k][j] % mod) % mod; } } } return z; }
3.单位矩阵
误区:单位矩阵是左上右下对角线上元素全为1,并不是所有元素全为1。
struct matrix { ll a[maxn][maxn]; matrix() { memset(a, 0, sizeof(a)); } //构造单位矩阵 inline void build() { for(int i = 1; i <= n; i ++) { a[i][i] = 1; } } };
P3390 【模板】矩阵快速幂
#include<bits/stdc++.h> using namespace std; #define ll long long const int maxn = 150; const int mod = 1e9 + 7; int n; ll k; struct matrix { ll a[maxn][maxn]; matrix() { memset(a, 0, sizeof(a)); } //构造单位矩阵 inline void build() { for(int i = 1; i <= n; i ++) { a[i][i] = 1; } } }m; //重载运算符 matrix operator *(const matrix &x, const matrix &y) { matrix z; for(int i = 1; i <= n; i ++) { for(int j = 1; j <= n; j ++) { for(int k = 1; k <= n; k ++) { z.a[i][j] = (z.a[i][j] + x.a[i][k] * y.a[k][j] % mod) % mod; } } } return z; } int main() { cin >> n >> k; for (int i = 1; i <= n; i ++) { for (int j = 1; j <= n; j ++) { cin >> m.a[i][j]; } } matrix ans; ans.build(); while(k) { if(k & 1) {//奇数(不能被2整除) ans = ans * m; } k >>= 1; m = m * m; } for(int i = 1; i <= n; i ++) { for(int j = 1; j <= n; j ++) { cout << ans.a[i][j] << " "; } cout << "\n"; } return 0; }
标签:matrix,int,ll,单位矩阵,maxn,ans,快速 From: https://www.cnblogs.com/coding-inspirations/p/16621506.html