什么是矩阵
简单来说,矩阵就是一个二位数组
矩阵的运算
1.矩阵的加法,减法
相应位置相加减
2.矩阵数乘
把一个数乘进矩阵
3.矩阵乘法(两个矩阵相乘)
x行y列*y行z列=x行z列
A乘B不一定等于B*A
不满足交换律,满足结合律
单位元
那矩阵的快速幂要怎么实现呢?先来了解单位元
单位元:如果x和y做运算,如果结果依旧是y,那么x就是单位元
不同运算的单位元:
加:0
乘:1
字符串:空串
与:true
或:false
矩阵的单位元就是单位矩阵:方阵,主对角线全为1,其他都是0
矩阵快速幂
矩阵快速幂就是把普通快速幂下面的数字换成矩阵
模板代码
struct Mat{
int a[2][2];
int r,c;
Mat(int _r=0,int _c=0){
r=_r,c=_c;
memset(a,0,sizeof a);
if(c==0)c=r;
}
void unit(){
memset(a,0,sizeof a);
for(int i=1;i<=r;i++){
a[i][i]=1;
}
}
Mat operator+(const Mat &t)const{
Mat ans(r,c);
for(int i=1;i<=r;i++){
for(int j=1;j<=c;j++){
ans.a[i][j]=a[i][j]+t.a[i][j];
}
}
return ans;
}
Mat operator-(const Mat &t)const{
Mat ans=*this;
for(int i=1;i<=r;i++){
for(int j=1;j<=c;j++){
ans.a[i][j]-=t.a[i][j];
}
}
return ans;
}
Mat operator*(const Mat &t)const{
Mat ans(r,t.c);
int n=r,m=t.c;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
for(int k=1;k<=c;k++){
ans.a[i][j]+=a[i][k]*t.a[k][j];
}
}
}
return ans;
}
Mat operator%(const int &t)const{
Mat ans=*this;
for(int i=1;i<=r;i++){
for(int j=1;j<=c;j++){
ans.a[i][j]%=t;
}
}
return ans;
}
Mat pow(ll b,ll p){
Mat ans(r,c),a=*this;
ans.unit();
while(b){
if(b&1)ans=ans*a%p;
a=a*a%p;
b>>=1;
}
return ans;
}
void print(){
for(int i=1;i<=r;i++){
for(int j=1;j<=c;j++){
cout<<a[i][j]<<' ';
}
cout<<'\n';
}
}
};