0
点赞
收藏
分享

微信扫一扫

矩阵快速幂(板子)

菜头粿子园 2022-02-07 阅读 81
#include<bits/stdc++.h>
using namespace std;

#define rep(i,l,r) for(int i=(l);i<=(r);i++)
#define per(i,l,r) for(int i=(l);i>=(r);i--)
#define ll long long
#define pii pair<int, int>
#define mset(s,t) memset(s,t,sizeof(t))
#define mcpy(s,t) memcpy(s,t,sizeof(t))
#define fir first
#define pb push_back
#define sec second

inline int read () {
	int x = 0, f = 0;
	char ch = getchar();
	while (!isdigit(ch)) f |= (ch=='-'),ch= getchar();
	while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
	return f?-x:x;
}
template<typename T> void print(T x) {
	if (x < 0) putchar('-'), x = -x;
	if (x >= 10) print(x/10);
	putchar(x % 10 + '0');
}

const int N = 1e2 + 10;
const int mod = 1e9 + 7;
ll n, k;
struct Matrix {
	ll c[N][N];
	Matrix () {
		for (int i =  1; i <= n; i ++) {
			for (int j = 1; j <= n;j ++)
			 c[i][j] = 0;
		}
	}	

}A, I;
	Matrix operator * (const Matrix & a, const Matrix & b) {
		Matrix re;
	    
		rep(i, 1, n)
			rep(j, 1, n)
				rep(k, 1, n)
					re.c[i][j] = (re.c[i][j] + a.c[i][k] * b.c[k][j] % mod) %mod;
		return re;
	}
void solve() {
	cin >> n >> k;
	rep(i, 1, n)
		rep(j, 1, n)
			cin >> A.c[i][j];
	
	rep(i, 1, n)
		 I.c[i][i] = 1;
	while (k) {
		if (k & 1) I = I * A;
		A = A * A;
		k >>= 1;
	}
    
	rep(i, 1, n)
		rep(j, 1, n)
		{
		    cout << I.c[i][j] << ' ';
		    if (j == n) puts("");
		}
}
int main () {
    int t;
    t = 1;
    while (t --) solve();
    return 0;
}

矩阵快速幂,注意要重载乘号的方式注意先后顺序,因为矩阵乘法不满足交换律

举报

相关推荐

0 条评论