题解
Sk=A+A1+A2+...+Ak
if k is even :
Sk=(A1+A2+…+Ak/2)+Ak/2(A1+A2+…+Ak/2) =Sk/2+Ak/2Sk/2 =Sk/2(E+Ak/2)
if k is odd :
Sk=Sk−1+Ak
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 30;
struct mat{
int M[N][N];
mat(){ memset(M, 0, sizeof(M)); }
};
int n, k, mod;
mat mul(mat A, mat B)
{
mat C;
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] + A.M[i][k] * B.M[k][j]) % mod;
return C;
}
mat add(mat A, mat B)
{
mat C;
for(int i = 0; i < N; ++i)
{
for(int j = 0; j < N; ++j)
{
C.M[i][j] = (A.M[i][j] + B.M[i][j]) % mod;
}
}
return C;
}
mat pow(mat A, int p)
{
mat E;
for(int i = 0; i < N; ++i) E.M[i][i] = 1;
while(p){
if(p & 1) E = mul(E, A);
A = mul(A, A);
p >>= 1;
}
return E;
}
mat solve(mat A, int k)
{
if(k == 1) return A;
if(k & 1) return add(pow(A, k), solve(A, k - 1));
mat E;
for(int i = 0; i < N; ++i) E.M[i][i] = 1;
mat T = add(pow(A, k >> 1), E);
return mul(solve(A, k >> 1), T);
}
int main()
{
mat A;
scanf("%d %d %d", &n, &k, &mod);
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
scanf("%d", &A.M[i][j]);
mat ans = solve(A, k);
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < n; ++j)
{
if(j) printf(" ");
printf("%d", ans.M[i][j]);
}
printf("\n");
}
return 0;
}