矩阵快速幂

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define YES cout<<"YES"<<endl;
#define NO  cout<<"NO"<<endl;
#define endl '\n'
#define io ios::sync_with_stdio(false)
#define tie cin.tie(0),cout.tie(0)
#define MOD 1000000007
//构建矩阵结构
int n,m;
struct matix{
	int c[101][101];
	matix(){memset(c,0,sizeof(c));}
}A,res;
//重载乘法
matix operator*(matix&x,matix&y){
	matix t;//临时矩阵 用于返回最后的结果
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			for(int k=1;k<=n;k++){
				t.c[i][j]=(t.c[i][j]+x.c[i][k]*y.c[k][j])%MOD;
			}
		}
	}
	return t;
}

void fastpow(int k){
	for(int i=1;i<=n;i++) res.c[i][i]=1;//res是答案
	while(k){
		if(k%2==1){
			res=res*A;
		}
		A=A*A;
		k/=2;
	}
	for(int i = 1; i <= n; i++) {
    for(int j = 1; j <= n; j++) {
        cout << res.c[i][j] << " ";
    }
    cout << endl;
}
}
signed main(){
    io,tie;
    cin>>n>>m;
    for(int i=1;i<=n;i++){
    	for(int j=1;j<=n;j++){
    		cin>>A.c[i][j];
    	}
    }
    fastpow(m);
    
    return 0;
}
posted @ 2025-02-27 21:59  Qacter  阅读(15)  评论(0)    收藏  举报