矩陣運算,矩陣快速冪,模板
阿新 • • 發佈:2019-01-30
#include<cstdio> #include<algorithm> #include<cstring> #include<iostream> using namespace std; #define MOD 1000000007 struct Mat{ int n,m; //行列 int mat[19][19]; }; Mat operator *(Mat a, Mat b) { //矩陣相乘 Mat c; memset(c.mat, 0, sizeof(c.mat)); c.n = a.n, c.m = b.m; for (int i = 1; i <= a.n; i++) { for (int j = 1; j <= b.m; j++) { for (int k = 1; k <= a.m; k++) { c.mat[i][j] += (a.mat[i][k] * b.mat[k][j]) % MOD; c.mat[i][j] = (c.mat[i][j] % MOD + MOD) % MOD; } } } return c; } Mat operator +(Mat a, Mat b) { //矩陣相加 Mat c; memset(c.mat, 0, sizeof(c.mat)); c.n = a.n, c.m = a.m; for (int i = 1; i <= a.n; i++) { for (int j = 1; j <= a.m; j++) { c.mat[i][j] = (a.mat[i][j] + b.mat[i][j]) % MOD; } } return c; } Mat operator ^(Mat a,int k){ //矩陣冪 Mat c; memset(c.mat,0,sizeof(c.mat)); c.n = a.n,c.m = a.n; for(int i=1;i<=a.n;i++)c.mat[i][i] = 1; while(k){ if(k&1){ c = c*a; } a = a*a; k>>=1; } return c; } void out(Mat a){ //輸出矩陣 for(int i=1;i<=a.n;i++){ for(int j=1;j<=a.m;j++){ printf(j==a.m? "%d\n":"%d ",a.mat[i][j]); } } } int main(){ Mat d; d.n=3,d.m=3; for(int i=1;i<=d.n;i++){ for(int j=1;j<=d.m;j++){ scanf("%d",&d.mat[i][j]); } } d=d^2; out(d); }