矩阵快速幂 - 倍增法
以及二分求和
(以上说法纯属个人理解方式)
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<map>
using namespace std;
const int maxn = 40 + 7;
int n;
struct M {
int m[maxn][maxn];
void init() {
memset(m, 0, sizeof m);
}
M() {}
//~M() {}
M(char e) {
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
m[i][j] = (i == j ? 1 : 0);
}
};
M a, ans;
M mod(M s) {
for(int i = 0; i < n; ++i)
for(int j = 0 ; j < n; ++j)
s.m[i][j] %= 10;
return s;
}
M sum(M a1, M a2) {
M c; c.init();
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
c.m[i][j] = (a1.m[i][j] + a2.m[i][j]) % 10;
}
}
return c;
}
M mul(M a1, M a2) {
M c; c.init();
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
for(int k = 0; k < n; ++k) {
c.m[i][j] = ( c.m[i][j] + (a1.m[i][k] * a2.m[k][j]))%10;
}
//c.m[i][j] %= 10;
}
}
return c;
}
M mi(int s) {
M E('e'), t; //t.init();
t = a;
while(s) {
if(s & 1) E = mul(E, t);
t = mul(t, t);
//mod(E), mod(t);
s /= 2;
}//cout << " 2333 " << endl;
mod(E);
return E;
}
M solve(int k) {
M ret; //ret.init();
M E('e');
if(k == 0) return E;
if(k == 1) return a;
ret = mul(sum(E, mi(k/2)), solve(k/2));
if(k & 1) ret = sum(ret, mi(k));
mod(ret);
return ret;
}
void print(M s) {
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
if(j) cout << " ";
cout << s.m[i][j]%10;
}
cout << endl;
}
cout << endl;
}
int main() {
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int k;
while(scanf("%d%d", &n, &k) && n ) {
a.init();//, ans.init();
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j) {
cin >> a.m[i][j];
a.m[i][j] %= 10;
}
ans = solve(k);
mod(ans);
print(ans);
}
return 0;
}
/*
5 512
0 0 0 2 0
0 2 2 2 2
0 0 2 2 0
1 1 1 1 1
1 1 1 1 1
*/