P3390 【模板】矩阵快速幂

原题传送门
题目大意:给定\(n\times n\)的矩阵\(A\),求\(A^k\),对矩阵每个元素模\(10^9+7\)

数据范围:\(n\le 100,k\le 10^{12},|A_{i,j}|\le 1000\)

矩阵乘法+快速幂
PS: 记得开\(longlong\)!!!

Code:

#include <bits/stdc++.h>
using namespace std;
const int N=1e2+10,mod=1e9+7;
typedef long long ll;
struct Mat{
	ll mat[N][N];
};
Mat mul(Mat a,Mat b,ll n){
	Mat c;
	memset(c.mat,0,sizeof(c.mat));
	for(int i=0;i<n;i++){
		for(int j=0;j<n;j++){
			for(int k=0;k<n;k++){
				c.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
				c.mat[i][j]%=mod;
			}
		}
	}
	return c;
}
Mat mat_power(Mat c,ll n,ll k){
	Mat ans;
	for(int i=0;i<n;i++) ans.mat[i][i]=1;
	for(;k;k>>=1){
		if(k&1) ans=mul(ans,c,n);
		c=mul(c,c,n);
	}
	return ans;
}
int main(){		
	ll n,k;
	cin>>n>>k;
	Mat c,ans;
	for(int i=0;i<n;i++){
		for(int j=0;j<n;j++){
			cin>>c.mat[i][j];
		}
	}
	ans=mat_power(c,n,k);
	for(int i=0;i<n;i++){
		for(int j=0;j<n;j++){
			cout<<ans.mat[i][j]<<" ";
		}
		cout<<endl; 
	}
	return 0;
}
posted @ 2021-12-14 16:42  Wraith-Fiee  阅读(31)  评论(0)    收藏  举报