矩阵及矩阵快速幂

什么是矩阵

简单来说,矩阵就是一个二位数组

矩阵的运算

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';
		}
	}
};

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值