矩阵运算模板,思路在注释里
#include<stdio.h>
//!!初值需修改为所需值!!
#define N 2
typedef struct _1 //gcc可能会出错
{ // 尽量用g++
__int64 mat[N][N];
int row;//行
int col;//列
}Matrix;
int mod = 19999997;
Matrix Mul(Matrix left,Matrix right);
Matrix Pow(Matrix x,int n);
Matrix MulMod(Matrix left,Matrix right);
Matrix PowMod(Matrix x,int n);
void Show(Matrix x);
Matrix Mul(Matrix left,Matrix right)
{
int n,i,j,k;
Matrix res;
if(left.col != right.row)
return res;
else
n = left.col;
res.row = left.row;
res.col = right.col;
for(i = 0 ; i < left.row ; i++)
{
for( j = 0 ; j < right.col; j++)
{
res.mat[i][j] = 0;
for( k = 0 ; k < n ; k++)
{
res.mat[i][j] += left.mat[i][k] * right.mat[k][j];
}
}
}
return res;
}
Matrix Pow(Matrix x,int n)
{
int i,j;
Matrix res ;
res.row = x.row;
res.col = x.col;
for(i = 0 ; i < res.row ;i++)
{
for(j = 0 ; j < res.col ; j++)
{
res.mat[i][j] = 0;
}
res.mat[i][i] = 1;
}
while(n)
{
if(n&1)//n % 2 == 1
res = Mul(res,x);
x = Mul(x,x);
n >>= 1;
}
return res;
}
Matrix MulMod(Matrix left,Matrix right)
{
int n,i,j,k;
Matrix res;
if(left.col != right.row)
return res;
else
n = left.col;
res.row = left.row;
res.col = right.col;
for(i = 0 ; i < left.row ; i++)
{
for( j = 0 ; j < right.col; j++)
{
res.mat[i][j] = 0;
for( k = 0 ; k < n ; k++)
{
res.mat[i][j] += (left.mat[i][k] * right.mat[k][j]) % mod;
}
res.mat[i][j] %= mod;
}
}
return res;
}
Matrix PowMod(Matrix x,int n)
{
int i,j;
Matrix res ;
res.row = x.row;
res.col = x.col;
for(i = 0 ; i < res.row ;i++)
{
for(j = 0 ; j < res.col ; j++)
{
res.mat[i][j] = 0;
}
res.mat[i][i] = 1;
}
while(n)
{
if(n&1)//n % 2 == 1
res = MulMod(res,x);
x = MulMod(x,x);
n >>= 1;
}
return res;
}
void Show(Matrix x)
{
int i,j;
for(i = 0 ; i < x.row ; i++)
{
for(j = 0 ; j < x.col ; j++)
{
printf("%d ",x.mat[i][j]);
}
printf("\n");
}
printf("\n");
}