牛客网考研机试题集合:矩阵幂

考点:矩阵乘法,快速矩阵幂

本题:不使用快速幂运算也不会超时


方法一:快速幂:和普通数据类型的操作类似

#include<bits/stdc++.h>
using namespace std;
const int MAXSIZE=1001;

struct Mat {
	int mat[MAXSIZE][MAXSIZE];
	int row,col;
};
Mat mul(Mat a,Mat b);
Mat powMat(Mat a,int k);
int main() {
	int n,k;
	while(cin>>n>>k) {
		Mat a;
		a.row=n;
		a.col=n;
		for(int i=0; i<n; i++) {
			for(int j=0; j<n; j++) {
				cin>>a.mat[i][j];
			}
		}
		Mat res;
		res=powMat(a,k);
		for(int i=0; i<n; i++) {
			for(int j=0; j<n; j++) {
				cout<<res.mat[i][j];
				if(j!=n-1) {
					cout<<" ";
				}
			}
			cout<<endl;
		}

	}
	return 0;
}
Mat mul(Mat a,Mat b) {
	Mat ans;
	ans.row=a.row;
	ans.col=b.col;
	memset(ans.mat,0,sizeof(ans.mat));
	for(int i=0; i<ans.row; i++) {
		for(int j=0; j<ans.col; j++) {
			for(int k=0; k<a.col; k++) {
				ans.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
			}
		}
	}
	return ans;
}
Mat powMat(Mat a,int k) {
	Mat ans;
	ans.row=a.row;
	ans.col=a.col;
	for(int i=0; i<a.row; i++) {
		for(int j=0; j<a.col; j++) {
			ans.mat[i][j]=(i==j);
		}
	}
	while(k) {
		if(k&1) {
			ans=mul(ans,a);
		}
		a=mul(a,a);
		k>>=1;
	}
    return ans;
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值